VSCode配置Go环境及Go mod使用

VSCode配置Go的代码补全相关功能

安装好Go相关插件,配置工具包

使用command+shift+P快捷键,然后键入

Go: Install/Update Tools

确定之后会执行安装

Installing github.com/mdempsky/gocode SUCCEEDED
Installing github.com/uudashr/gopkgs/cmd/gopkgs SUCCEEDED
Installing github.com/ramya-rao-a/go-outline SUCCEEDED
Installing github.com/acroca/go-symbols SUCCEEDED
Installing golang.org/x/tools/cmd/guru SUCCEEDED
Installing golang.org/x/tools/cmd/gorename SUCCEEDED
Installing github.com/go-delve/delve/cmd/dlv SUCCEEDED
Installing github.com/stamblerre/gocode SUCCEEDED
Installing github.com/rogpeppe/godef SUCCEEDED
Installing golang.org/x/tools/cmd/goimports SUCCEEDED
Installing golang.org/x/lint/golint SUCCEEDED
Installing golang.org/x/tools/cmd/gopls SUCCEEDED
Installing github.com/cweill/gotests/... SUCCEEDED
Installing github.com/fatih/gomodifytags SUCCEEDED
Installing github.com/josharian/impl SUCCEEDED
Installing github.com/davidrjenni/reftools/cmd/fillstruct SUCCEEDED
Installing github.com/haya14busa/goplay/cmd/goplay SUCCEEDED
Installing github.com/godoctor/godoctor SUCCEEDED

Reload VS Code window to use the Go language server
All tools successfully installed. You're ready to Go :).

调整VSCode的配置

    "go.autocompleteUnimportedPackages": true,
    "go.useLanguageServer": true,
    "go.inferGopath": true,
    "go.docsTool": "godoc",
    "go.gocodePackageLookupMode": "go",
    "go.gotoSymbol.includeImports": true,
    "go.useCodeSnippetsOnFunctionSuggest": true, //使用代码片段提示
    "go.useCodeSnippetsOnFunctionSuggestWithoutType": true,
    "go.formatTool": "goimports", //代码格式化
    "go.buildOnSave": true, //保存代码时自动编译
    "go.lintOnSave": true, //保存代码时优化
    "go.vetOnSave": false, //保存代码时检查潜在错误
    "go.coverOnSave": false //保存代码时执行测试

Go mod使用

  • 1. 初始化项目
➜  ~ mkdir hello2
➜  ~ cd hello2
➜  hello2 go mod init hello2
go: creating new go.mod: module hello2
➜  hello2 ls
go.mod
➜  hello2 cat go.mod
module hello2

go 1.12
  • 2. 添加依赖

新建main.go文件,并执行go run main.go

package main

import (
	"net/http"
	"github.com/gin-gonic/gin"
)

func main()  {
	r := gin.Default()

	r.GET("/", func(c *gin.Context)  {
		c.String(http.StatusOK,"hello,world")
	})

	r.Run(":8080")
}
  • 3. 查看Go mod
module hello2

go 1.12

require github.com/gin-gonic/gin v1.4.0

go.mod 提供了module, require、replace和exclude 四个命令

  • module 语句指定包的名字(路径)
  • require 语句指定的依赖项模块
  • replace 语句可以替换依赖项模块
  • exclude 语句可以忽略依赖项模块

可参考 go mod 使用|掘金

推荐阅读