If you know nothing about Go, here are a few key or interesting points that make it a great tool for our toolbox:
A few things that you might use every day that were built with Go include things like: Docker, Kubernetes, Terraform, Prometheus, Grafana, Caddy, Ngrok, Minio, Etcd
To install Go, use brew:
brew install go
To start a new Go project, follow these steps:
go mod init <module-name>
where <module-name>
is the name of your project.
Note: The module name is usually the repository URL but can be any name such as myapp
or gitlab.com/limelyte/client/myapp
In general, Go doesn't care how you structure your project and it can be as simple as having a single main.go file for small utility applications. That said, when creating a new Go project it is important to follow a consistent structure, especially for larger projects. Here is a recommended project structure for a Go application that follows best practices and works well for most applications:
myapp/
├── cmd/ --> Main binaries for this project under cmd. You can have multiple binaries in a single project.
│ └── myapp/
│ └── main.go --> Entry point of this binary. This will be the "main" package.
│ └── myapp2/
│ └── main.go --> Entry point of another binary. This will also be the "main" package for this binary.
├── internal/ --> Private application and library code specific to this project
│ ├── handlers/ --> HTTP request handlers or controllers. If this is package "handlers" it will be referenced as "myapp/internal/handler"
│ ├── models/ --> Data models: package "models" referenced as "myapp/internal/models"
│ ├── service/ --> Other business logic, services, etc. referenced as "myapp/internal/service"
│ ├── templates/ --> HTML templates
│ └── util/ --> Utility functions: referenced as "myapp/internal/util"
├── pkg/ --> Public application and library code that can be used by other projects
│ └── mypackage/ This may not be used in all projects
├── configs/ --> Configuration files
│ └── config.yaml
├── go.mod --> Go module file, this is auto-generated
├── go.sum --> Go module dependencies, this is auto-generated
├── .env --> Environment variables
├── Makefile --> Makefile for build automation
└── README.md --> Project documentation / readme
A simple command line application structured similarly could omit the internal
, pkg
, and configs
directories if they are not needed as outlined below:
myapp/
├── cmd/
│ └── myapp/
│ └── main.go
├── go.mod
├── go.sum
└── README.md
To run your Go application in the above structure, you can use the following command from the root of your project:
go run ./cmd/myapp/*.go
This will build and run the myapp binary and will ensure that all dependencies are included.
To add a new dependency to your Go project, use the following command:
go get <dependency>
.env
file.