Visual Studio Code, Modules and Golang Language Server

Since Go 1.11, modules are the official way of managing dependencies in Go. The transition is not as smooth as it should be as it is in a very early stage. The feature is planned to be finalized with Go 1.14.

This articles explains the setup and recommends settings for Visual Studio Code.

go.mod basics

A module is a collection of related Go packages that are versioned together. All dependencies and their exact versions of your package imports are stored in the go.mod file.

See this Github page for more in-depth information on modules.

Here is an examplariy go.mod file.

The specified module is my-project/my-repo. The used version of Go is 1.12. Within this package, three imports are used.

module my-project/my-repo
go 1.12
require ( v1.3.3 // indirect v1.4.0 v1.4.1 // indirect

There are a few options for getting a specific dependency:

# by branch name
go get
# by git tag
go get
# by git commit
go get

Go module setup in Visual Studio Code

Enable Go modules on your machine with

# Set environment variable to "on" (other choices: "auto", "off")
setx GO111MODULE on

To enable module support in Visual Studio Code, add the following to your IDE settings (press CTRL+,):

"go.useLanguageServer": true

This will trigger VS Code to install the go package gopls (The Go Language Server). Visual Studio uses gopls, an implementation of the Language Server Protocol server for Go. It supports features, such as

  • Autocompletion
  • Jump to definition
  • Signature help
  • Hover
  • Document symbols
  • References
  • Rename

It is currently in alpha state, so it is not stable. To install or update gopls, run

go get

However, you can also use the VSCode command Go: Install/Update Tools to install and update all available Go tools. It is located under “View” -> “Command Palette”.

After enabling this feature, I had several problems to a point where Visual Studio Code was almost not usable anymore (on file save, an old version was loaded and all was lost; go-to-definition not working or very slow, and several other problems).

Therefore, it is recommended to look out for updates of the Go tools. However, the following additional settings in VS Code resolved my problems.

"go.languageServerExperimentalFeatures": {
 "autoComplete": true,
 "documentSymbols": true,
 "findReferences": true,
 "format": false,
 "goToDefinition": true,
 "goToTypeDefinition": true,
 "hover": true,
 "signatureHelp": true,
 "rename": true,
 "workspaceSymbols": true,
 "diagnostics": true, // for diagnostics as you type

Some more settings which I find helpful for my daily work with Go.

"go.testOnSave": true,
"go.lintOnSave": "package",
"go.formatTool": "goimports",
"go.testFlags": [
"go.lintOnSave": "file",
"go.autocompleteUnimportedPackages": true,
"[go]": {
    "editor.codeActionsOnSave": {
       "source.organizeImports": false