How do I properly use go modules in vscode?

Rafał Radecki picture Rafał Radecki · Jan 14, 2020 · Viewed 16.9k times · Source

I have used vscode 1.41.1 on my mac for a few months and it worked good until I started to use go modules for dependency management. At the moment I am rewriting a simple tool and introduce packages for separate functionalities.

My code structure looks like this:

├── bmr.go -> package main & main(), uses below packages
├── check
│   ├── check.go -> package check
│   └── check_test.go
├── go.mod
├── go.sum
├── push
│   ├── push.go -> package push
│   └── push_test.go
└── s3objects
    ├── s3objects.go -> package s3objects
    └── s3objects_test.go

My go.mod file looks like this:

module github.com/some-org/business-metrics-restore

go 1.13

require (
        github.com/aws/aws-sdk-go v1.28.1
        github.com/go-redis/redis v6.15.6+incompatible
        github.com/sirupsen/logrus v1.4.2
        github.com/spf13/viper v1.6.1
        github.com/stretchr/testify v1.4.0
        golang.org/x/sys v0.0.0-20200113162924-86b910548bc1
)

All is fine when I invoke go test/run/build commands from the shell. But when I use 'Debug' -> 'Run Without Debugging' I get:

go: finding github.com/some-org/business-metrics-restore/push latest
go: finding github.com/some-org/business-metrics-restore latest
go: finding github.com/some-org/business-metrics-restore/check latest
go: finding github.com/some-org/business-metrics-restore/s3objects latest
build command-line-arguments: cannot load github.com/some-org/business-metrics-restore/check: module github.com/some-org/business-metrics-restore@latest found (v0.0.0-20191022092726-d1a52439dad8), but does not contain package github.com/some-org/business-metrics-restore/check
Process exiting with code: 1

My code currently is in a feature branch and d1a52439dad8 is the first (init) and only commit on master. No code for the tool (incl. 3 mentioned non main packages) is in the master branch. The problem here is that for some reason as you see above vscode fetches state from master and I cannot override this behaviour.

Can anyone help me?

Thanks!

Best Regards, Rafal.

Answer

Juan Schwindt picture Juan Schwindt · Jul 1, 2020

I realized that if the go.mod is not at the root of your project VSCode does not work properly. I have an AWS SAM project with the following structure:

├── Makefile
├── README.md
├── nic-update
│   ├── go.mod
│   ├── go.sum
│   ├── main.go
│   ├── main_test.go
│   └── r53service
│       └── r53.go
├── samconfig.toml
└── template.yaml

and the only way it works if by starting VSCode from the nic-update directory.

My go.mod has the following content:

require (
    github.com/aws/aws-lambda-go v1.13.3
    github.com/aws/aws-sdk-go v1.32.12
)

module github.com/jschwindt/ddns-route53/nic-update

go 1.14