Setting up a dev container for Go
- Primary author: Maxim Chadaev
- Reviewer: Daniel Henderson
Initial Setup
- To create a project, run
mkdir <name>
andcd <project-name>
for your specific project - Then, you need to intiialize a git repo with
git init
- Add a readme file to make your first commit with
- Then, to create a Remote Repository on Github, login to Github and go to the 'Create a New Repository Page`
- Choose your settings and details, and choose the same name as your project and create the repository
- Then, add the Github repository as a remote with
git remote add origin https://github.com/<your-username>/<project-name>
. Make sure you replace<your-username>
and<project-name>
with your GitHub username and project name respectively. - Check the default branch with
git branch
and if it is not main, rename it withgit branch -M main
. - Then push it with
git push --set-upstream origin main
Set up Devcontainer
- Create a directory
.devcontainer
. - Create a dev container configuration
.devcontainer/devcontainer.json
. - Make sure you have Docker installed. If you use Windows, make sure your project is on a partition shared with Docker.
Dev Container configuration
{
"name": "Your project Dev",
"image": "mcr.microsoft.com/devcontainers/go:latest",
"extensions": [
"golang.go",
],
"settings": {
"go.useLanguageServer": true
},
"postCreateCommand": "go mod download",
}
It also runs go mod download after the container is set up to download your Go dependencies when the container is ready.
Using Go Commands
- Verify the Go Installation
go version
- Initialize a Go module
go mod init my_project_name
-
Make a main.go file in your folder and paste this code:
-
Run your Go code
go run main.go
or build a binarygo build -o myapp main.go
Unlike go run, go build generates a reusable binary that can be executed multiple times or shared with others without needing recompilation, similar to how gcc compiles source code into an executable binary.
Launching it
Launch it by opening the VS Code command palette and selecting Remote-Containers: Open folder in container...
and choose the current folder.
This will build the Docker image, install the VS Code dependencies in there, and bind mount everything for you!
Finally, you have a terminal running a beautiful zsh inside VS Code (open a terminal if you don’t see it).
Pushing to GitHub
Now you can commit and push these changes to github. Stage your changes and commit them, with an appropriate message, before pushing to your remote repository.
Now, you are done!