NotePublic/Software/Development/Language/Go/Linux_下搭建_Go_开发环境.md

2.3 KiB

Linux 下搭建 Go 开发环境

1. 安装和配置

1.1. 安装

# Ubuntu Snap (版本新)
snap install go --classic
# Ubuntu (版本旧)
sudo apt install golang

# Manjaro
sudo pacman -S go

1.2. 配置

# 配置环境,将 /Path/to/Go 替换为自己实际的 go 目录
echo "export GOPATH=/Path/to/Go" >> ~/.bashrc
echo "export GOBIN=$GOPATH/bin" >> ~/.bashrc
echo "export PATH=$GOBIN:$PATH" >> ~/.bashrc
# 可运行 go env 查看gol环境变量
go env
# 开启 GO111MODULE 并设置代理
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn
# 安装基础包
go get -v github.com/golang/tools
ln -s $GOPATH/src/github.com/golang/tools $GOPATH/src/golang.org/x/tools
# 安装扩展包
go install github.com/ramya-rao-a/go-outline@latest
go install github.com/go-delve/delve/cmd/dlv@latest
go install github.com/mdempsky/gocode@latest
go install github.com/uudashr/gopkgs/v2/cmd/gopkgs@latest
go install github.com/rogpeppe/godef@latest
go install github.com/sqs/goreturns@latest
go install github.com/cweill/gotests/gotests@latest
go install github.com/fatih/gomodifytags@latest
go install github.com/josharian/impl@latest
go install github.com/haya14busa/goplay/cmd/goplay@latest
go install honnef.co/go/tools/cmd/staticcheck@latest
go install golang.org/x/tools/gopls@latest
go install golang.org/x/tools/cmd/godoc@latest
go install golang.org/x/tools/cmd/goimports@latest

1.3. VSCode 配置

修改 User Setting 的 go.gopath 为 $GOPATH。

1.4. 移除不使用的包

到 $GOPATH/pkg 下删除对应的源码,然后使用:

go clean -i -r

刷新一下即可。

2. 第一个 Go 程序

/**
 * @file    hello.go
 */
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

测试和编译方法如下:

$ go run hello.go
Hello, World!

$ go build hello.go
$ ls
hello    hello.go

$ ./hello
Hello, World!

3. 常用 Go 包

go install github.com/cjbassi/gotop@latest

4. 常见问题

4.1. Snap 安装后 VSCode Go 插件报 Failed to run '/snap/bin/go env' error

进入 VSCode 用户配置(JSON),添加:

"go.alternateTools": {
    "go": "/snap/go/current/bin/go"
},

5. 外部参考资料

  1. How to remove package installed with go get