This extension is highly configurable, and as such, offers a number of settings. These can be configured by modifying your User or Workspace Settings.
To navigate to your settings, open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P) and search for "settings". The simplest way to modify your settings is through "Preferences: Open Settings (UI)".
For tuning the features provided by gopls
, see the section for gopls
settings.
The settings described below are up-to-date as of January 2021. We do our best to keep documentation current, but if a setting is missing, you can always consult the full list in the Extensions view. Documentation for each setting should also be visible in the Settings UI.
To view the list of settings:
- Navigate to the Extensions view (Ctrl+Shift+X).
- Find the Go extension and click on it to open the Extension Editor.
- Click on the
Feature Contributions
tab. - Scroll through the list under
Settings
.
This extension runs a few third-party command-line tools found from the locations determined by the PATH
or Path
environment variable, and the settings such as "go.alternateTools"
or "go.toolsGopath"
. Configuring them in workspace settings allows users to conveniently select a different set of tools based on project's need, but also allows attackers to run arbitrary binaries on your machine if they successfuly convince you to open a random repository. In order to reduce the security risk, the extension reads those settings from user settings by default. If the repository can be trusted and workspace settings must be used, you can mark the workspace as a trusted workspace using the "Go: Toggle Workspace Trust Flag"
command.
Tags and options configured here will be used by the Add Tags command to add tags to struct fields. If promptForTags is true, then user will be prompted for tags and options. By default, json tags are added.
Properties | Description |
---|---|
options |
Comma separated tag=options pairs to be used by Go: Add Tags command Default: "json=omitempty" |
promptForTags |
If true, Go: Add Tags command will prompt the user to provide tags, options, transform values instead of using the configured values Default: false |
tags |
Comma separated tags to be used by Go: Add Tags command Default: "json" |
template |
Custom format used by Go: Add Tags command for the tag value to be applied Default: "" |
transform |
Transformation rule used by Go: Add Tags command to add tags Allowed Options: snakecase , camelcase , lispcase , pascalcase , keep Default: "snakecase" |
Default:
{
"options" : "json=omitempty",
"promptForTags" : false,
"tags" : "json",
"template" : "",
"transform" : "snakecase",
}
Alternate tools or alternate paths for the same tools used by the Go extension. Provide either absolute path or the name of the binary in GOPATH/bin, GOROOT/bin or PATH. Useful when you want to use wrapper script for the Go tools or versioned tools from https://gopkg.in. When specified as a workspace setting, the setting is used only when the workspace is marked trusted with "Go: Toggle Workspace Trust Flag".
Properties | Description |
---|---|
dlv |
Alternate tool to use instead of the dlv binary or alternate path to use for the dlv binary. Default: "dlv" |
go |
Alternate tool to use instead of the go binary or alternate path to use for the go binary. Default: "go" |
go-outline |
Alternate tool to use instead of the go-outline binary or alternate path to use for the go-outline binary. Default: "go-outline" |
gopkgs |
Alternate tool to use instead of the gopkgs binary or alternate path to use for the gopkgs binary. Default: "gopkgs" |
gopls |
Alternate tool to use instead of the gopls binary or alternate path to use for the gopls binary. Default: "gopls" |
Include unimported packages in auto-complete suggestions. Not applicable when using the language server.
Default: false
Flags to go build
/go test
used during build-on-save or running tests. (e.g. ["-ldflags='-s'"]) This is propagated to the language server if gopls.build.buildFlags
is not specified.
Compiles code on file save using 'go build' or 'go test -c'. Options are 'workspace', 'package', or 'off'. Not applicable when using the language server's diagnostics. See 'go.languageServerExperimentalFeatures.diagnostics' setting.
Allowed Options: package
, workspace
, off
Default: "package"
The Go build tags to use for all commands, that support a -tags '...'
argument. When running tests, go.testTags will be used instead if it was set. This is propagated to the language server if gopls.build.buildFlags
is not specified.
Default: ""
When generating code coverage, the value for -covermode. 'default' is the default value chosen by the 'go test' command.
Allowed Options: default
, set
, count
, atomic
Default: "default"
If true, runs 'go test -coverprofile' on save and shows test coverage.
Default: false
If true, shows test coverage when Go: Test Function at cursor command is run.
Default: false
If true, shows test coverage when Go: Test Single File command is run.
Default: false
If true, shows test coverage when Go: Test Package command is run.
Default: true
When generating code coverage, should counts be shown as --374--
Default: false
This option lets you choose the way to display code coverage. Choose either to highlight the complete line or to show a decorator in the gutter. You can customize the colors and borders for the former and the style for the latter.
Properties | Description |
---|---|
coveredBorderColor |
Color to use for the border of covered code. |
coveredGutterStyle |
Gutter style to indicate covered code. Allowed Options: blockblue , blockred , blockgreen , blockyellow , slashred , slashgreen , slashblue , slashyellow , verticalred , verticalgreen , verticalblue , verticalyellow |
coveredHighlightColor |
Color in the rgba format to use to highlight covered code. |
type |
Allowed Options: highlight , gutter |
uncoveredBorderColor |
Color to use for the border of uncovered code. |
uncoveredGutterStyle |
Gutter style to indicate covered code. Allowed Options: blockblue , blockred , blockgreen , blockyellow , slashred , slashgreen , slashblue , slashyellow , verticalred , verticalgreen , verticalblue , verticalyellow |
uncoveredHighlightColor |
Color in the rgba format to use to highlight uncovered code. |
Default:
{
"coveredBorderColor" : "rgba(64,128,128,0.5)",
"coveredGutterStyle" : "blockblue",
"coveredHighlightColor" : "rgba(64,128,128,0.5)",
"type" : "highlight",
"uncoveredBorderColor" : "rgba(128,64,64,0.25)",
"uncoveredGutterStyle" : "slashyellow",
"uncoveredHighlightColor" : "rgba(128,64,64,0.25)",
}
Use these options to control whether only covered or only uncovered code or both should be highlighted after running test coverage
Allowed Options: showCoveredCodeOnly
, showUncoveredCodeOnly
, showBothCoveredAndUncoveredCode
Default: "showBothCoveredAndUncoveredCode"
Delve settings that applies to all debugging sessions. Debug configuration in the launch.json file will override these values.
Properties | Description |
---|---|
apiVersion |
Delve Api Version to use. Default value is 2. Allowed Options: 1 , 2 Default: 2 |
debugAdapter |
Select which debug adapter to use by default. This is also used for choosing which debug adapter to use when no launch.json is present and with codelenses. Allowed Options: legacy , dlv-dap Default: "dlv-dap" |
dlvLoadConfig |
LoadConfig describes to delve, how to load values from target's memory. Ignored by 'dlv-dap'. Default: { <pre>"followPointers" : true,<br/>"maxArrayValues" : 64,<br/>"maxStringLen" : 64,<br/>"maxStructFields" : -1,<br/>"maxVariableRecurse" : 1,</pre>} |
showGlobalVariables |
Boolean value to indicate whether global package variables should be shown in the variables pane or not. Default: false |
substitutePath |
An array of mappings from a local path to the remote path that is used by the debuggee. The debug adapter will replace the local path with the remote path in all of the calls. Overriden by remotePath (in attach request). |
Default:
{
"apiVersion" : 2,
"debugAdapter" : "legacy",
"dlvLoadConfig" : {
"followPointers" : true,
"maxArrayValues" : 64,
"maxStringLen" : 64,
"maxStructFields" : -1,
"maxVariableRecurse" : 1,
},
"showGlobalVariables" : false,
"substitutePath" : [],
}
If true, tests will not run concurrently. When a new test run is started, the previous will be cancelled.
Default: false
Pick 'godoc' or 'gogetdoc' to get documentation. Not applicable when using the language server.
Allowed Options: godoc
, gogetdoc
, guru
Default: "godoc"
Experimental Feature: Enable/Disable entries from the context menu in the editor.
Properties | Description |
---|---|
addImport |
If true, adds command to import a package to the editor context menu Default: true |
addTags |
If true, adds command to add configured tags from struct fields to the editor context menu Default: true |
benchmarkAtCursor |
If true, adds command to benchmark the test under the cursor to the editor context menu Default: true |
debugTestAtCursor |
If true, adds command to debug the test under the cursor to the editor context menu Default: true |
fillStruct |
If true, adds command to fill struct literal with default values to the editor context menu Default: true |
generateTestForFile |
If true, adds command to generate unit tests for current file to the editor context menu Default: true |
generateTestForFunction |
If true, adds command to generate unit tests for function under the cursor to the editor context menu Default: true |
generateTestForPackage |
If true, adds command to generate unit tests for currnt package to the editor context menu Default: true |
playground |
If true, adds command to upload the current file or selection to the Go Playground Default: true |
removeTags |
If true, adds command to remove configured tags from struct fields to the editor context menu Default: true |
testAtCursor |
If true, adds command to run the test under the cursor to the editor context menu Default: true |
testCoverage |
If true, adds command to run test coverage to the editor context menu Default: true |
testFile |
If true, adds command to run all tests in the current file to the editor context menu Default: true |
testPackage |
If true, adds command to run all tests in the current package to the editor context menu Default: true |
toggleTestFile |
If true, adds command to toggle between a Go file and its test file to the editor context menu Default: true |
Default:
{
"addImport" : true,
"addTags" : true,
"benchmarkAtCursor" : false,
"debugTestAtCursor" : true,
"fillStruct" : false,
"generateTestForFile" : false,
"generateTestForFunction" : true,
"generateTestForPackage" : false,
"playground" : true,
"removeTags" : false,
"testAtCursor" : true,
"testCoverage" : true,
"testFile" : false,
"testPackage" : false,
"toggleTestFile" : true,
}
Feature level setting to enable/disable code lens for references and run/debug tests
Properties | Description |
---|---|
references |
If true, enables the references code lens. Uses guru. Recalculates when there is change to the document followed by scrolling. Unnecessary when using the language server; use the call graph feature instead. Default: false |
runtest |
If true, enables code lens for running and debugging tests Default: true |
Default:
{
"references" : false,
"runtest" : true,
}
Flags to pass to format tool (e.g. ["-s"]). Not applicable when using the language server.
Not applicable when using the language server. Choosing 'goimports', 'goreturns', or 'gofumports' will add missing imports and remove unused imports.
Allowed Options:
default
: If the language server is enabled, format via the language server, which already supports gofmt, goimports, goreturns, and gofumpt. Otherwise, goimports.gofmt
: Formats the file according to the standard Go style.goimports
: Organizes imports and formats the file with gofmt.goformat
: Configurable gofmt, see https://github.com/mbenkmann/goformat.gofumpt
: Stricter version of gofmt, see https://github.com/mvdan/gofumpt.gofumports
: Applies gofumpt formatting and organizes imports.
Default: "default"
Additional command line flags to pass to gotests
for generating tests.
Enable gocode's autobuild feature. Not applicable when using the language server.
Default: false
Additional flags to pass to gocode. Not applicable when using the language server.
Default: [-builtin -ignore-case -unimported-packages]
Used to determine the Go package lookup rules for completions by gocode. Only applies when using nsf/gocode. Latest versions of the Go extension uses mdempsky/gocode by default. Not applicable when using the language server.
Allowed Options: go
, gb
, bzl
Default: "go"
Specify GOPATH here to override the one that is set as environment variable. The inferred GOPATH from workspace root overrides this, if go.inferGopath is set to true. When specified as a workspace setting, the setting is used only when the workspace is marked trusted with "Go: Toggle Workspace Trust Flag".
Specifies the GOROOT to use when no environment variable is set. When specified as a workspace setting, the setting is used only when the workspace is marked trusted with "Go: Toggle Workspace Trust Flag".
Folder names (not paths) to ignore while using Go to Symbol in Workspace feature. Not applicable when using the language server.
If false, the standard library located at $GOROOT will be excluded while using the Go to Symbol in File feature. Not applicable when using the language server.
Default: false
If false, the import statements will be excluded while using the Go to Symbol in File feature. Not applicable when using the language server.
Default: false
Infer GOPATH from the workspace root. This is ignored when using Go Modules. When specified as a workspace setting, the setting is used only when the workspace is marked trusted with "Go: Toggle Workspace Trust Flag".
Default: false
If true, then -i
flag will be passed to go build
everytime the code is compiled. Since Go 1.10, setting this may be unnecessary unless you are in GOPATH mode and do not use the language server.
Default: false
Temporary flag to enable/disable diagnostics from the language server. This setting will be deprecated soon. Please see and response to Issue 50.
Properties | Description |
---|---|
diagnostics |
If true, the language server will provide build, vet errors and the extension will ignore the buildOnSave , vetOnSave settings. Default: true |
Default:
{
"diagnostics" : true,
}
Flags like -rpc.trace and -logfile to be used while running the language server.
Flags to pass to Lint tool (e.g. ["-min_confidence=.8"])
Lints code on file save using the configured Lint tool. Options are 'file', 'package', 'workspace' or 'off'.
Allowed Options: file
, package
, workspace
, off
Default: "package"
Specifies Lint tool name.
Allowed Options: staticcheck
, golint
, golangci-lint
, revive
Default: "staticcheck"
Use gotype on the file currently being edited and report any semantic or syntactic errors found after configured delay. Not applicable when using the language server.
Properties | Description |
---|---|
delay |
The number of milliseconds to delay before execution. Resets with each keystroke. Default: 500 |
enabled |
If true, runs gotype on the file currently being edited and reports any semantic or syntactic errors found. Disabled when the language server is enabled. Default: false |
Default:
{
"delay" : 500,
"enabled" : false,
}
The logging level the extension logs at, defaults to 'error'
Allowed Options: off
, error
, info
, verbose
Default: "error"
The flags configured here will be passed through to command goplay
Properties | Description |
---|---|
openbrowser |
Whether to open the created Go Playground in the default browser Default: true |
run |
Whether to run the created Go Playground after creation Default: true |
share |
Whether to make the created Go Playground shareable Default: true |
Default:
{
"openbrowser" : true,
"run" : true,
"share" : true,
}
Tags and options configured here will be used by the Remove Tags command to remove tags to struct fields. If promptForTags is true, then user will be prompted for tags and options. By default, all tags and options will be removed.
Properties | Description |
---|---|
options |
Comma separated tag=options pairs to be used by Go: Remove Tags command Default: "json=omitempty" |
promptForTags |
If true, Go: Remove Tags command will prompt the user to provide tags and options instead of using the configured values Default: false |
tags |
Comma separated tags to be used by Go: Remove Tags command Default: "json" |
Default:
{
"options" : "",
"promptForTags" : false,
"tags" : "",
}
Apply the Go & PATH environment variables used by the extension to all integrated terminals.
Default: true
Absolute path to a file containing environment variables definitions. File contents should be of the form key=value.
Environment variables that will be passed to the process that runs the Go tests
If true, test log messages associated with a given location will be shown as a single message.
Default: true
Control whether packages in the test explorer are presented flat or nested.
Allowed Options: flat
, nested
Default: "flat"
Include benchmarks when running all tests in a group.
Default: false
Flags to pass to go test
. If null, then buildFlags will be used. This is not propagated to the language server.
Run 'go test' on save for current package. It is not advised to set this to true
when you have Auto Save enabled.
Default: false
The Go build tags to use for when running tests. If null, then buildTags will be used.
Specifies the timeout for go test in ParseDuration format.
Default: "30s"
Environment variables that will be passed to the tools that run the Go tools (e.g. CGO_CFLAGS)
Location to install the Go tools that the extension depends on if you don't want them in your GOPATH. When specified as a workspace setting, the setting is used only when the workspace is marked trusted with "Go: Toggle Workspace Trust Flag".
Automatically update the tools used by the extension, without prompting the user.
Default: false
Specify whether to prompt about new versions of Go and the Go tools (currently, only gopls
) the extension depends on
Allowed Options:
proxy
: keeps notified of new releases by checking the Go module proxy (GOPROXY)local
: checks only the minimum tools versions required by the extensionoff
: completely disables version check (not recommended)
Default: "proxy"
Trace the communication between VS Code and the Go language server.
Allowed Options: off
, messages
, verbose
Default: "off"
Complete functions with their parameter signature, including the variable type. Not propagated to the language server.
Default: false
Complete functions with their parameter signature, excluding the variable types. Use gopls.usePlaceholders
when using the language server.
Default: false
Use go.toolsManagement.checkForUpdates
instead.
When enabled, the extension automatically checks the Go proxy if there are updates available for Go and the Go tools (at present, only gopls) it depends on and prompts the user accordingly
Default: true
Use the Go language server "gopls" from Google for powering language features like code navigation, completion, refactoring, formatting & diagnostics.
Default: true
Flags to pass to go tool vet
(e.g. ["-all", "-shadow"])
Vets code on file save using 'go tool vet'. Not applicable when using the language server's diagnostics. See 'go.languageServerExperimentalFeatures.diagnostics' setting.
Allowed Options: package
, workspace
, off
Default: "package"
Customize gopls
behavior by specifying the gopls' settings in this section. For example,
"gopls" : {
"build.directoryFilters": ["-node_modules"]
...
}
This section is directly read by gopls
. See the gopls
section section for the full list of gopls
settings.
Configure the default Go language server ('gopls'). In most cases, configuring this section is unnecessary. See the documentation for all available settings.
(Experimental) allowImplicitNetworkAccess disables GOPROXY=off, allowing implicit module downloads rather than requiring user action. This option will eventually be removed.
Default: false
(Experimental) allowModfileModifications disables -mod=readonly, allowing imports from out-of-scope modules. This option will eventually be removed.
Default: false
buildFlags is the set of flags passed on to the build system when invoked.
It is applied to queries like go list
, which is used when discovering files.
The most common use is to set -tags
.
If unspecified, values of go.buildFlags, go.buildTags
will be propagated.
directoryFilters can be used to exclude unwanted directories from the
workspace. By default, all directories are included. Filters are an
operator, +
to include and -
to exclude, followed by a path prefix
relative to the workspace folder. They are evaluated in order, and
the last filter that applies to a path controls whether it is included.
The path prefix can be empty, so an initial -
excludes everything.
Examples:
Exclude node_modules: -node_modules
Include only project_a: -
(exclude everything), +project_a
Include only project_a, but not node_modules inside it: -
, +project_a
, -project_a/node_modules
env adds environment variables to external commands run by gopls
, most notably go list
.
(Experimental) expandWorkspaceToModule instructs gopls
to adjust the scope of the
workspace to find the best available module root. gopls
first looks for
a go.mod file in any parent directory of the workspace folder, expanding
the scope to that directory if it exists. If no viable parent directory is
found, gopls will check if there is exactly one child directory containing
a go.mod file, narrowing the scope to that directory if it exists.
Default: true
(Experimental) experimentalPackageCacheKey controls whether to use a coarser cache key for package type information to increase cache hits. This setting removes the user's environment, build flags, and working directory from the cache key, which should be a safe change as all relevant inputs into the type checking pass are already hashed into the key. This is temporarily guarded by an experiment because caching behavior is subtle and difficult to comprehensively test.
Default: true
(Experimental) experimentalTemplateSupport opts into the experimental support for template files.
Default: false
(Experimental) experimentalUseInvalidMetadata enables gopls to fall back on outdated package metadata to provide editor features if the go command fails to load packages for some reason (like an invalid go.mod file). This will eventually be the default behavior, and this setting will be removed.
Default: false
(Experimental) experimentalWorkspaceModule opts a user into the experimental support for multi-module workspaces.
Default: false
(Experimental) memoryMode controls the tradeoff gopls
makes between memory usage and
correctness.
Values other than Normal
are untested and may break in surprising ways.
Allowed Options:
DegradeClosed
:"DegradeClosed"
: In DegradeClosed mode,gopls
will collect less information about packages without open files. As a result, features like Find References and Rename will miss results in such packages.Normal
Default: "Normal"
gofumpt indicates if we should run gofumpt formatting.
Default: false
local is the equivalent of the goimports -local
flag, which puts
imports beginning with this string after third-party packages. It should
be the prefix of the import path whose imports should be grouped
separately.
Default: ""
codelenses overrides the enabled/disabled state of code lenses. See the "Code Lenses" section of the Settings page for the list of supported lenses.
Example Usage:
"gopls": {
...
"codelens": {
"generate": false, // Don't show the `go generate` lens.
"gc_details": true // Show a code lens toggling the display of gc's choices.
}
...
}
Properties | Description |
---|---|
gc_details |
Toggle the calculation of gc annotations. Default: false |
generate |
Runs go generate for a given directory. Default: true |
regenerate_cgo |
Regenerates cgo definitions. Default: true |
test |
Runs go test for a specific set of test or benchmark functions. Default: false |
tidy |
Runs go mod tidy for a module. Default: true |
upgrade_dependency |
Upgrades a dependency in the go.mod file for a module. Default: true |
vendor |
Runs go mod vendor for a module. Default: true |
(For Debugging) completionBudget is the soft latency goal for completion requests. Most requests finish in a couple milliseconds, but in some cases deep completions can take much longer. As we use up our budget we dynamically reduce the search scope to ensure we return timely results. Zero means unlimited.
Default: "100ms"
(Experimental) experimentalPostfixCompletions enables artifical method snippets such as "someSlice.sort!".
Default: true
(Advanced) matcher sets the algorithm that is used when calculating completion
candidates.
Allowed Options: CaseInsensitive
, CaseSensitive
, Fuzzy
Default: "Fuzzy"
placeholders enables placeholders for function parameters or struct fields in completion responses.
Default: false
analyses specify analyses that the user would like to enable or disable. A map of the names of analysis passes that should be enabled/disabled. A full list of analyzers that gopls uses can be found here.
Example Usage:
...
"analyses": {
"unreachable": false, // Disable the unreachable analyzer.
"unusedparams": true // Enable the unusedparams analyzer.
}
...
Properties | Description |
---|---|
asmdecl |
report mismatches between assembly files and Go declarations Default: true |
assign |
check for useless assignments This checker reports assignments of the form x = x or a[i] = a[i]. These are almost always useless, and even when they aren't they are usually a mistake. Default: true |
atomic |
check for common mistakes using the sync/atomic package The atomic checker looks for assignment statements of the form: x = atomic.AddUint64(&x, 1) which are not atomic. Default: true |
atomicalign |
check for non-64-bits-aligned arguments to sync/atomic functions Default: true |
bools |
check for common mistakes involving boolean operators Default: true |
buildtag |
check that +build tags are well-formed and correctly located Default: true |
cgocall |
detect some violations of the cgo pointer passing rules Check for invalid cgo pointer passing. This looks for code that uses cgo to call C code passing values whose types are almost always invalid according to the cgo pointer sharing rules. Specifically, it warns about attempts to pass a Go chan, map, func, or slice to C, either directly, or via a pointer, array, or struct. Default: true |
composites |
check for unkeyed composite literals This analyzer reports a diagnostic for composite literals of struct types imported from another package that do not use the field-keyed syntax. Such literals are fragile because the addition of a new field (even if unexported) to the struct will cause compilation to fail. As an example, err = &net.DNSConfigError{err} should be replaced by: err = &net.DNSConfigError{Err: err} Default: true |
copylocks |
check for locks erroneously passed by value Inadvertently copying a value containing a lock, such as sync.Mutex or sync.WaitGroup, may cause both copies to malfunction. Generally such values should be referred to through a pointer. Default: true |
deepequalerrors |
check for calls of reflect.DeepEqual on error values The deepequalerrors checker looks for calls of the form: reflect.DeepEqual(err1, err2) where err1 and err2 are errors. Using reflect.DeepEqual to compare errors is discouraged. Default: true |
errorsas |
report passing non-pointer or non-error values to errors.As The errorsas analysis reports calls to errors.As where the type of the second argument is not a pointer to a type implementing error. Default: true |
fieldalignment |
find structs that would use less memory if their fields were sorted This analyzer find structs that can be rearranged to use less memory, and provides a suggested edit with the optimal order. Note that there are two different diagnostics reported. One checks struct size, and the other reports "pointer bytes" used. Pointer bytes is how many bytes of the object that the garbage collector has to potentially scan for pointers, for example: struct { uint32; string } have 16 pointer bytes because the garbage collector has to scan up through the string's inner pointer. struct { string; *uint32 } has 24 pointer bytes because it has to scan further through the *uint32. struct { string; uint32 } has 8 because it can stop immediately after the string pointer. Default: false |
fillreturns |
suggested fixes for "wrong number of return values (want %d, got %d)" This checker provides suggested fixes for type errors of the type "wrong number of return values (want %d, got %d)". For example: func m() (int, string, *bool, error) {will turn into func m() (int, string, *bool, error) { This functionality is similar to https://github.com/sqs/goreturns. Default: true |
fillstruct |
note incomplete struct initializations This analyzer provides diagnostics for any struct literals that do not have any fields initialized. Because the suggested fix for this analysis is expensive to compute, callers should compute it separately, using the SuggestedFix function below. Default: true |
httpresponse |
check for mistakes using HTTP responses A common mistake when using the net/http package is to defer a function call to close the http.Response Body before checking the error that determines whether the response is valid: resp, err := http.Head(url) This checker helps uncover latent nil dereference bugs by reporting a diagnostic for such mistakes. Default: true |
ifaceassert |
detect impossible interface-to-interface type assertions This checker flags type assertions v.(T) and corresponding type-switch cases in which the static type V of v is an interface that cannot possibly implement the target interface T. This occurs when V and T contain methods with the same name but different signatures. Example: var v interface { The Read method in v has a different signature than the Read method in io.Reader, so this assertion cannot succeed. Default: true |
loopclosure |
check references to loop variables from within nested functions This analyzer checks for references to loop variables from within a function literal inside the loop body. It checks only instances where the function literal is called in a defer or go statement that is the last statement in the loop body, as otherwise we would need whole program analysis. For example: for i, v := range s { See: https://golang.org/doc/go_faq.html#closures_and_goroutines Default: true |
lostcancel |
check cancel func returned by context.WithCancel is called The cancellation function returned by context.WithCancel, WithTimeout, and WithDeadline must be called or the new context will remain live until its parent context is cancelled. (The background context is never cancelled.) Default: true |
nilfunc |
check for useless comparisons between functions and nil A useless comparison is one like f == nil as opposed to f() == nil. Default: true |
nilness |
check for redundant or impossible nil comparisons The nilness checker inspects the control-flow graph of each function in a package and reports nil pointer dereferences, degenerate nil pointers, and panics with nil values. A degenerate comparison is of the form x==nil or x!=nil where x is statically known to be nil or non-nil. These are often a mistake, especially in control flow related to errors. Panics with nil values are checked because they are not detectable by if r := recover(); r != nil { This check reports conditions such as: if f == nil { // impossible condition (f is a function) and: p := &v and: if p == nil { and: if p == nil { Default: false |
nonewvars |
suggested fixes for "no new vars on left side of :=" This checker provides suggested fixes for type errors of the type "no new vars on left side of :=". For example: z := 1will turn into z := 1 Default: true |
noresultvalues |
suggested fixes for "no result values expected" This checker provides suggested fixes for type errors of the type "no result values expected". For example: func z() { return nil }will turn into func z() { return } Default: true |
printf |
check consistency of Printf format strings and arguments The check applies to known functions (for example, those in package fmt) as well as any detected wrappers of known functions. A function that wants to avail itself of printf checking but is not found by this analyzer's heuristics (for example, due to use of dynamic calls) can insert a bogus call: if false { The -funcs flag specifies a comma-separated list of names of additional known formatting functions or methods. If the name contains a period, it must denote a specific function using one of the following forms: dir/pkg.Function Otherwise the name is interpreted as a case-insensitive unqualified identifier such as "errorf". Either way, if a listed name ends in f, the function is assumed to be Printf-like, taking a format string before the argument list. Otherwise it is assumed to be Print-like, taking a list of arguments with no format string. Default: true |
shadow |
check for possible unintended shadowing of variables This analyzer check for shadowed variables. A shadowed variable is a variable declared in an inner scope with the same name and type as a variable in an outer scope, and where the outer variable is mentioned after the inner one is declared. (This definition can be refined; the module generates too many false positives and is not yet enabled by default.) For example: func BadRead(f *os.File, buf []byte) error { Default: false |
shift |
check for shifts that equal or exceed the width of the integer Default: true |
simplifycompositelit |
check for composite literal simplifications An array, slice, or map composite literal of the form: []T{T{}, T{}}will be simplified to: []T{{}, {}} This is one of the simplifications that "gofmt -s" applies. Default: true |
simplifyrange |
check for range statement simplifications A range of the form: for x, _ = range v {...}will be simplified to: for x = range v {...} A range of the form: for _ = range v {...}will be simplified to: for range v {...} This is one of the simplifications that "gofmt -s" applies. Default: true |
simplifyslice |
check for slice simplifications A slice expression of the form: s[a:len(s)]will be simplified to: s[a:] This is one of the simplifications that "gofmt -s" applies. Default: true |
sortslice |
check the argument type of sort.Slice sort.Slice requires an argument of a slice type. Check that the interface{} value passed to sort.Slice is actually a slice. Default: true |
stdmethods |
check signature of methods of well-known interfaces Sometimes a type may be intended to satisfy an interface but may fail to do so because of a mistake in its method signature. For example, the result of this WriteTo method should be (int64, error), not error, to satisfy io.WriterTo: type myWriterTo struct{...}func (myWriterTo) WriteTo(w io.Writer) error { ... } This check ensures that each method whose name matches one of several well-known interface methods from the standard library has the correct signature for that interface. Checked method names include: Format GobEncode GobDecode MarshalJSON MarshalXML Default: true |
stringintconv |
check for string(int) conversions This checker flags conversions of the form string(x) where x is an integer (but not byte or rune) type. Such conversions are discouraged because they return the UTF-8 representation of the Unicode code point x, and not a decimal string representation of x as one might expect. Furthermore, if x denotes an invalid code point, the conversion cannot be statically rejected. For conversions that intend on using the code point, consider replacing them with string(rune(x)). Otherwise, strconv.Itoa and its equivalents return the string representation of the value in the desired base. Default: true |
structtag |
check that struct field tags conform to reflect.StructTag.Get Also report certain struct tags (json, xml) used with unexported fields. Default: true |
testinggoroutine |
report calls to (*testing.T).Fatal from goroutines started by a test. Functions that abruptly terminate a test, such as the Fatal, Fatalf, FailNow, and Skip{,f,Now} methods of *testing.T, must be called from the test goroutine itself. This checker detects calls to these functions that occur within a goroutine started by the test. For example: func TestFoo(t *testing.T) { go func() { t.Fatal("oops") // error: (*T).Fatal called from non-test goroutine }() } Default: true |
tests |
check for common mistaken usages of tests and examples The tests checker walks Test, Benchmark and Example functions checking malformed names, wrong signatures and examples documenting non-existent identifiers. Please see the documentation for package testing in golang.org/pkg/testing for the conventions that are enforced for Tests, Benchmarks, and Examples. Default: true |
undeclaredname |
suggested fixes for "undeclared name: <>" This checker provides suggested fixes for type errors of the type "undeclared name: <>". It will insert a new statement: "<> := ". Default: true |
unmarshal |
report passing non-pointer or non-interface values to unmarshal The unmarshal analysis reports calls to functions such as json.Unmarshal in which the argument type is not a pointer or an interface. Default: true |
unreachable |
check for unreachable code The unreachable analyzer finds statements that execution can never reach because they are preceded by an return statement, a call to panic, an infinite loop, or similar constructs. Default: true |
unsafeptr |
check for invalid conversions of uintptr to unsafe.Pointer The unsafeptr analyzer reports likely incorrect uses of unsafe.Pointer to convert integers to pointers. A conversion from uintptr to unsafe.Pointer is invalid if it implies that there is a uintptr-typed word in memory that holds a pointer value, because that word will be invisible to stack copying and to the garbage collector. Default: true |
unusedparams |
check for unused parameters of functions The unusedparams analyzer checks functions to see if there are any parameters that are not being used. To reduce false positives it ignores: - methods - parameters that do not have a name or are underscored - functions in test files - functions with empty bodies or those with just a return stmt Default: false |
unusedresult |
check for unused results of calls to some functions Some functions like fmt.Errorf return a result and have no side effects, so it is always a mistake to discard the result. This analyzer reports calls to certain functions in which the result of the call is ignored. The set of functions may be controlled using flags. Default: true |
unusedwrite |
checks for unused writes The analyzer reports instances of writes to struct fields and arrays that are never read. Specifically, when a struct object or an array is copied, its elements are copied implicitly by the compiler, and any element write to this copy does nothing with the original object. For example: type T struct { x int } Another example is about non-pointer receiver: type T struct { x int } Default: false |
(Experimental) annotations specifies the various kinds of optimization diagnostics that should be reported by the gc_details command.
Properties | Description |
---|---|
bounds |
"bounds" controls bounds checking diagnostics. Default: true |
escape |
"escape" controls diagnostics about escape choices. Default: true |
inline |
"inline" controls diagnostics about inlining choices. Default: true |
nil |
"nil" controls nil checks. Default: true |
(Advanced) diagnosticsDelay controls the amount of time that gopls waits after the most recent file modification before computing deep diagnostics. Simple diagnostics (parsing and type-checking) are always run immediately on recently modified packages.
This option must be set to a valid duration string, for example "250ms"
.
Default: "250ms"
(Experimental) experimentalWatchedFileDelay controls the amount of time that gopls waits for additional workspace/didChangeWatchedFiles notifications to arrive, before processing all such notifications in a single batch. This is intended for use by LSP clients that don't support their own batching of file system notifications.
This option must be set to a valid duration string, for example "100ms"
.
Default: "0s"
(Experimental) staticcheck enables additional analyses from staticcheck.io.
Default: false
hoverKind controls the information that appears in the hover text.
SingleLine and Structured are intended for use only by authors of editor plugins.
Allowed Options:
FullDocumentation
NoDocumentation
SingleLine
Structured
:"Structured"
is an experimental setting that returns a structured hover format. This format separates the signature from the documentation, so that the client can do more manipulation of these fields.
This should only be used by clients that support this behavior.SynopsisDocumentation
Default: "FullDocumentation"
linkTarget controls where documentation links go. It might be one of:
"godoc.org"
"pkg.go.dev"
If company chooses to use its own godoc.org
, its address can be used as well.
Default: "pkg.go.dev"
linksInHover toggles the presence of links to documentation in hover.
Default: true
importShortcut specifies whether import statements should link to
documentation or go to definitions.
Allowed Options: Both
, Definition
, Link
Default: "Both"
(Advanced) symbolMatcher sets the algorithm that is used when finding workspace symbols.
Allowed Options: CaseInsensitive
, CaseSensitive
, Fuzzy
Default: "Fuzzy"
(Advanced) symbolStyle controls how symbols are qualified in symbol responses.
Example Usage:
"gopls": {
...
"symbolStyle": "dynamic",
...
}
Allowed Options:
Dynamic
:"Dynamic"
uses whichever qualifier results in the highest scoring match for the given symbol query. Here a "qualifier" is any "/" or "." delimited suffix of the fully qualified symbol. i.e. "to/pkg.Foo.Field" or just "Foo.Field".Full
:"Full"
is fully qualified symbols, i.e. "path/to/pkg.Foo.Field".Package
:"Package"
is package qualified symbols i.e. "pkg.Foo.Field".
Default: "Dynamic"
(Experimental) semanticTokens controls whether the LSP server will send semantic tokens to the client.
Default: false
(For Debugging) verboseOutput enables additional debug logging.
Default: false