Go 语言环境安装
三平台装 Go、配 GOPATH 与代理、验证安装。
Key Points装完只需关注三个变量:`GOROOT`(安装位置)、`GOPATH`(工作区)、`GOPROXY`(模块代理)。
安装
Bash
# macOS
brew install go
# Linux(也可用包管理器)
wget https://go.dev/dl/go1.22.8.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.8.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
# Windows
winget install GoLang.Go验证
Bash
go version
go env GOROOT GOPATH GOPROXYOutput
go version go1.22.8 windows/amd64
C:\Program Files\Go
C:\Users\Administrator\go
https://proxy.golang.org,direct国内必配:模块代理
Bash
go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOSUMDB=off
go env -w GO111MODULE=onWithout a proxy, go get frequently times out on GitHub. direct is the fallback. GOSUMDB=off disables the checksum database (often unreachable in China); keep it on in production.
三个目录
| Variable | Meaning | Default |
|---|---|---|
GOROOT | Go 的安装目录 | 随安装包 |
GOPATH | 工作区,第三方包与 bin 在此 | ~/go |
GOMODCACHE | 模块缓存 | $GOPATH/pkg/mod |
第一个项目
Bash
mkdir hello && cd hello
go mod init example.com/helloGo
package main
import "fmt"
func main() {
fmt.Println("你好,Go")
}Bash
go run .
go build -o hello
./helloOutput
你好,Go
你好,GoThe module path in
go mod init need not exist, but use a domain you control (github.com/you/project); otherwise publishing will conflict later.安装
Bash
# macOS
brew install go
# Linux(也可用包管理器)
wget https://go.dev/dl/go1.22.8.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.8.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
# Windows
winget install GoLang.Go验证
Bash
go version
go env GOROOT GOPATH GOPROXYOutput
go version go1.22.8 windows/amd64
C:\Program Files\Go
C:\Users\Administrator\go
https://proxy.golang.org,direct国内必配:模块代理
Bash
go env -w GOPROXY=https://goproxy.cn,direct
go env -w GOSUMDB=off
go env -w GO111MODULE=on不配代理时 go get 拉 GitHub 上的包经常超时。direct 是兜底:代理失败时直连源站。GOSUMDB=off 关掉校验和数据库(国内常连不上),生产环境建议保留校验。
三个目录
| 变量 | 含义 | 默认 |
|---|---|---|
GOROOT | Go 的安装目录 | 随安装包 |
GOPATH | 工作区,第三方包与 bin 在此 | ~/go |
GOMODCACHE | 模块缓存 | $GOPATH/pkg/mod |
第一个项目
Bash
mkdir hello && cd hello
go mod init example.com/helloGo
package main
import "fmt"
func main() {
fmt.Println("你好,Go")
}Bash
go run .
go build -o hello
./helloOutput
你好,Go
你好,Gogo mod init 里的模块路径不需要真实存在,但建议用你能控制的域名(如 github.com/you/project),否则以后发布给别人用会冲突。