DEV Community

Cover image for How to Set Up a Go Development Environment with VS Code
Stella Achar Oiro
Stella Achar Oiro

Posted on

How to Set Up a Go Development Environment with VS Code

Go, also known as Golang, is a statically typed, compiled programming language designed for simplicity, efficiency, and reliability. Its concurrency features and performance make it ideal for cloud applications, microservices, and backend systems. Visual Studio Code (VS Code) provides excellent support for Go development through its extensions and integrated tools.

This article guides you through setting up a complete Go development environment with VS Code, configuring it for cloud development, and establishing best practices for efficient coding. By the end of this guide, you will have a fully functional Go workspace ready for developing cloud applications.

Prerequisites

Before beginning, ensure you have:

  • A computer running Windows 10/11, macOS, or a Linux distribution
  • Administrative access to install software
  • Internet connection for downloading necessary packages
  • Basic familiarity with command-line operations

Install Go

First, install the Go programming language on your system.

  1. Visit the official Go downloads page.

  2. Download the installer for your operating system.

  3. Run the installer and follow the on-screen instructions.

  4. Verify the installation by opening a terminal or command prompt and running:

    $ go version
    

    You should see output displaying the installed Go version.

  5. Set up your Go workspace by creating a directory structure. While Go modules have reduced the importance of the traditional GOPATH structure, it's still useful to have a dedicated workspace:

    $ mkdir -p ~/go/{bin,pkg,src}
    
  6. Add the Go binary directory to your PATH by adding the following to your shell profile file (.bashrc, .zshrc, or equivalent):

    $ export PATH=$PATH:$HOME/go/bin
    
  7. Apply the changes:

    $ source ~/.bashrc  # or source ~/.zshrc
    

Set Up VS Code for Go Development

Visual Studio Code provides excellent support for Go through its extensions.

Install VS Code

  1. Visit the VS Code download page.

  2. Download and install the version for your operating system.

  3. Launch VS Code after installation.

Install the Go Extension

  1. Open the Extensions view by clicking the Extensions icon in the Activity Bar on the side of the window or by pressing Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (macOS).

  2. Search for "Go" in the Extensions marketplace.

  3. Look for the extension published by the "Go Team at Google" and click Install.

    VS Code Go Extension

Go for Visual Studio Code

Install Go Tools

The Go extension relies on several tools for features like code completion, formatting, and debugging.

  1. Open the Command Palette with Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS).

  2. Type "Go: Install/Update Tools" and select this command when it appears.

  3. Check all available tools in the list and click OK to install them.

    $ Installing github.com/ramya-rao-a/go-outline SUCCEEDED
    $ Installing github.com/cweill/gotests/... SUCCEEDED
    $ Installing github.com/fatih/gomodifytags SUCCEEDED
    $ Installing github.com/josharian/impl SUCCEEDED
    $ Installing github.com/haya14busa/goplay/cmd/goplay SUCCEEDED
    $ Installing github.com/go-delve/delve/cmd/dlv SUCCEEDED
    $ Installing honnef.co/go/tools/cmd/staticcheck SUCCEEDED
    $ Installing golang.org/x/tools/gopls SUCCEEDED
    $ Installing golang.org/x/lint/golint SUCCEEDED
    

Configure VS Code Settings for Go

Customize your Go development environment by configuring VS Code settings.

  1. Open settings by pressing Ctrl+, (Windows/Linux) or Cmd+, (macOS).

  2. Search for "Go" to see available Go-specific settings.

  3. Consider enabling these recommended settings by adding them to your settings.json file:

    {
        "go.useLanguageServer": true,
        "go.formatTool": "goimports",
        "go.lintOnSave": "package",
        "editor.formatOnSave": true,
        "[go]": {
            "editor.codeActionsOnSave": {
                "source.organizeImports": true
            }
        }
    }
    

Create Your First Go Project

Now that your environment is set up, create a simple Go project to verify everything works correctly.

Initialize a Go Module

  1. Create a new directory for your project:

    $ mkdir -p ~/projects/hello-go
    $ cd ~/projects/hello-go
    
  2. Initialize a new Go module:

    $ go mod init example.com/hello
    

    This creates a go.mod file that tracks your dependencies.

Write a Simple Program

  1. Create a new file named main.go:

    $ touch main.go
    
  2. Open the project in VS Code:

    $ code .
    
  3. Add the following code to main.go:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        fmt.Println("Hello, Go!")
        fmt.Println("Current time:", time.Now().Format(time.RFC1123))
    }
    
  4. Save the file and run the program:

    $ go run main.go
    

    You should see output similar to:

    Hello, Go!
    Current time: Mon, 04 Mar 2025 15:04:05 PST
    

Debug Your Go Code

VS Code's debugger integration makes troubleshooting Go code straightforward.

  1. Set a breakpoint by clicking in the editor margin next to a line number.

  2. Open the Run and Debug view by clicking the Run icon in the Activity Bar or pressing Ctrl+Shift+D (Windows/Linux) or Cmd+Shift+D (macOS).

  3. Click "create a launch.json file" and select "Go" as the environment.

  4. Run the debugger by clicking the green play button or pressing F5.

Configure for Cloud Development

Set up your Go environment to work with cloud services and serverless functions.

Set Up for Serverless Development

  1. Install the necessary packages for working with serverless functions:

    $ go get github.com/aws/aws-lambda-go/lambda
    

    [!NOTE]
    While this package references AWS, the concepts apply to serverless functions across cloud providers.

  2. Create a sample serverless function:

    package main
    
    import (
        "context"
        "fmt"
        "github.com/aws/aws-lambda-go/lambda"
    )
    
    type Event struct {
        Name string `json:"name"`
    }
    
    type Response struct {
        Message string `json:"message"`
    }
    
    func HandleRequest(ctx context.Context, event Event) (Response, error) {
        return Response{
            Message: fmt.Sprintf("Hello, %s!", event.Name),
        }, nil
    }
    
    func main() {
        lambda.Start(HandleRequest)
    }
    

Manage Cloud Credentials Securely

When working with cloud services, securely managing credentials is crucial.

  1. Install a credential management tool suitable for your OS:

    $ go install github.com/99designs/aws-vault@latest
    
  2. Create a .gitignore file to prevent accidentally committing sensitive information:

    $ echo ".env\n*.pem\n*.key\ncredentials.json" > .gitignore
    
  3. Consider using environment variables for configuration:

    package main
    
    import (
        "fmt"
        "os"
    )
    
    func main() {
        region := os.Getenv("CLOUD_REGION")
        if region == "" {
            region = "us-west-1" // Default region
        }
        fmt.Printf("Using cloud region: %s\n", region)
    }
    

Best Practices for Go Development

Adopt these best practices to ensure your Go code is maintainable, efficient, and follows community standards.

Code Organization

Structure your projects for clarity and maintainability:

  1. Use packages to organize related functionality:

    myproject/
    ├── cmd/
    │   └── server/
    │       └── main.go
    ├── internal/
    │   ├── auth/
    │   │   └── auth.go
    │   └── database/
    │       └── database.go
    ├── pkg/
    │   └── utils/
    │       └── utils.go
    ├── go.mod
    └── go.sum
    
  2. Follow the standard Go project layout:

    • cmd/: Main applications
    • internal/: Private application and library code
    • pkg/: Library code that's safe for external use
    • api/: API definitions (protobuf, OpenAPI, etc.)

Testing Setup

Go has built-in testing capabilities that integrate seamlessly with VS Code:

  1. Create test files with names ending in _test.go:

    $ touch utils_test.go
    
  2. Write a simple test:

    package main
    
    import "testing"
    
    func TestHello(t *testing.T) {
        got := "Hello, Go!"
        want := "Hello, Go!"
        if got != want {
            t.Errorf("got %q, want %q", got, want)
        }
    }
    
  3. Run tests from the terminal:

    $ go test ./...
    
  4. Or use VS Code's test explorer to run and debug tests visually.

Continuous Integration

Set up continuous integration to automatically test your code:

  1. Create a .github/workflows directory for GitHub Actions:

    $ mkdir -p .github/workflows
    
  2. Add a basic workflow file for Go:

    name: Go
    
    on:
      push:
        branches: [ main ]
      pull_request:
        branches: [ main ]
    
    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
        - uses: actions/checkout@v3
        - name: Set up Go
          uses: actions/setup-go@v3
          with:
            go-version: 1.21
        - name: Build
          run: go build -v ./...
        - name: Test
          run: go test -v ./...
    

Conclusion

You now have a fully configured Go development environment with VS Code ready for cloud application development. This setup provides code completion, debugging, testing, and all the tools needed for efficient Go programming.

As your projects grow in complexity, consider exploring advanced topics such as:

  • Creating and deploying Lambda functions using Go
  • Working with cloud storage services from Go applications
  • Using the AWS Toolkit in VS Code for cloud resource management

By following this guide, you've established a solid foundation for Go development that follows industry best practices and supports cloud application deployment.

Top comments (0)