Summary of Useful Go Commands
go run
: Compile and run code in one step.go build
: Compile code into an executable binary.go test
: Run tests.go fmt
: Format code according to Go's style.go install
: Install a binary from your Go code.go get
: Download and install dependencies.go mod
: Manage Go modules (dependencies).go clean
: Clean up build artifacts.go doc
: View documentation.go env
: View environment variables.go tool
: Run various Go tools (likepprof
orvet
).go version
: Check the installed Go version.go vet
: Analyze code for potential issues.go build -race
: Run with race detection to catch concurrency bugs.
GOOS
and GOARCH
environment variables are used to control cross-compilation—the ability to build executables for different operating systems and architectures. By setting these variables, you can compile Go code on one platform (e.g., Linux) and generate a binary for another platform (e.g., Windows or macOS).- GOOS=windows GOARCH=386 go build -o myapp_win32.exe
Project Structure:
myapp/
├── cmd/
│ ├── app1/
│ │ └── main.go # Entry point for app1
│ ├── app2/
│ │ └── main.go # Entry point for app2
│ └── cli-tool/
│ └── main.go # Entry point for a command-line tool
├── internal/
│ └── service/
│ └── service.go # Internal code used by cmd apps
├── pkg/
│ └── utils/
│ └── utils.go # Shared utility functions
├── go.mod
├── go.sum
└── README.md
go run main.go - to run go project
go mod tidy - for removing unused dependencies
go get github.com/gin-gonic/gin - to download dependency
go mod init <module-name> - to intialize module
go mod vendor - command in Go is used to create a
vendor/
directory in your Go project, where it copies all the dependencies (modules) that your project relies on. This directory includes the source code of the dependencies, which makes your project self-contained in terms of its dependencies. It is particularly useful for scenarios where you want to ensure that your project works offline or when you need to bundle all your dependencies in a single place for deployment or versioning.