DEV Community

Joris Conijn for AWS Community Builders

Posted on • Updated on • Originally published at binx.io

How to use AWS SAM with Go in Visual Studio Code

Setup Visual Studio Code as your IDE to build and deploy an AWS SAM stack using Go. I recently started to experiment with Go and the best way to learn is to play with it and build something. So I decided to build a simple application. During this process I ran into the problem that my IDE did not like having many go modules within one project.

Project layout

With AWS SAM you can build and deploy your stack or via a CI/CD pipeline, the process is the same. First you perform a sam build. This will compile the source code for each AWS::Serverless::Function in the template.yaml. Followed by sam deploy. This will upload the artifacts and deploy the template using AWS CloudFormation.

The problem that I faced was that each function needs a go.mod in the source folder. Visual Studio Code expects a single go.mod file in the project.

Project Structure

As a result imports in the unit test do not get recognized:

Sample code of the unit test without workspace

  • The RequestEvent struct.
  • The handler method.
  • The ResponseEvent struct. The reason for this is that the IDE has set the GOPATH to the root of the project. Therefor the imports are not correct. By using Workspace Folders you can change this behavior so that each folder has it’s own scope.

From Go 1.16+ the default build mode has switched from GOPATH to Go modules.

To do this you need to create a workspace.code-workspace file. Place it in the root of your project with the following content:

{
    "folders": [
        {
            "path": "functions/api"
        },
        {
            "path": "functions/confirm"
        },
        {
            "path": "functions/ship"
        },
        {
            "path": "functions/stock"
        },
        {
            "path": "."
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Now because each Go module lives within it’s own scope the imports are correct. As a result you are able to navigate through the code using the ⌘ click action.

Conclusion

When you deal with many Go modules within one project it is important to configure your IDE. This will improve readability, reduces errors and increases your development speed!

Top comments (0)