A comprehensive reference for essential Go packages organized by category with real go get commands and practical examples.
Installation & Setup
Install Go
# Linux/Ubuntu
wget https://golang.org/dl/go1.21.0.linux-amd64.tar.gz
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
# macOS with Homebrew
brew install go
# Verify installation
go version
Initialize Project
mkdir myproject && cd myproject
go mod init github.com/username/myproject
go get -u github.com/gin-gonic/gin
go mod tidy
Web Frameworks
| Library | Command | Purpose |
|---|
| Gin | go get -u github.com/gin-gonic/gin | High-performance HTTP web framework |
| Echo | go get -u github.com/labstack/echo/v4 | Minimalist web framework |
| Fiber | go get -u github.com/gofiber/fiber/v2 | Express-inspired web framework |
| Chi | go get -u github.com/go-chi/chi/v5 | Lightweight router for HTTP services |
| GORM | go get -u gorm.io/gorm | ORM library for databases |
Gin Example
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.POST("/users", func(c *gin.Context) {
var user map[string]interface{}
c.BindJSON(&user)
c.JSON(201, user)
})
r.Run(":8080")
}
Database Drivers & ORMs
| Library | Command | Purpose |
|---|
| GORM | go get -u gorm.io/gorm | Object-relational mapping |
| GORM PostgreSQL | go get -u gorm.io/driver/postgres | PostgreSQL driver for GORM |
| GORM MySQL | go get -u gorm.io/driver/mysql | MySQL driver for GORM |
| database/sql | Built-in | SQL database driver interface |
| sqlc | go install github.com/kyleconroy/sqlc/cmd/sqlc@latest | Generate type-safe SQL code |
GORM Database Connection
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func main() {
dsn := "host=localhost user=postgres password=password dbname=mydb port=5432"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("Failed to connect to database")
}
// Define model
type User struct {
ID uint
Name string
Email string
}
// Auto migrate
db.AutoMigrate(&User{})
}
| Library | Command | Purpose |
|---|
| Cobra | go get -u github.com/spf13/cobra | CLI command framework |
| Viper | go get -u github.com/spf13/viper | Configuration management |
| urfave/cli | go get -u github.com/urfave/cli/v2 | Command line app framework |
| Kingpin | go get -u gopkg.in/alecthomas/kingpin.v2 | Command-line parser |
Cobra CLI Example
cobra-cli new myapp
cd myapp
cobra-cli add serve
cobra-cli add config
package cmd
import "github.com/spf13/cobra"
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "My awesome app",
Run: func(cmd *cobra.Command, args []string) {
println("App started")
},
}
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Start the server",
Run: func(cmd *cobra.Command, args []string) {
println("Server running on :8080")
},
}
func init() {
rootCmd.AddCommand(serveCmd)
}
Testing Frameworks
| Library | Command | Purpose |
|---|
| Testify | go get -u github.com/stretchr/testify | Testing assertions and mocks |
| GoMock | go get -u github.com/golang/mock/gomock | Mock generation |
| Ginkgo | go get -u github.com/onsi/ginkgo/v2 | BDD testing framework |
| Table-driven | Built-in | Pattern for parameterized tests |
Testify Example
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Add(a, b int) int {
return a + b
}
func TestAdd(t *testing.T) {
assert.Equal(t, 5, Add(2, 3))
assert.NotEqual(t, 10, Add(2, 3))
}
JSON & Data Encoding
| Library | Command | Purpose |
|---|
| encoding/json | Built-in | Standard JSON marshaling |
| json-iterator/go | go get -u github.com/json-iterator/go | High-performance JSON parser |
| Protocol Buffers | go get -u github.com/protocolbuffers/protobuf-go | Efficient serialization |
| MessagePack | go get -u github.com/msgpack/msgpack-go | Binary serialization format |
JSON Marshaling
package main
import (
"encoding/json"
"fmt"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
}
func main() {
user := User{ID: 1, Name: "John", Email: "john@example.com"}
// Marshal to JSON
jsonData, _ := json.MarshalIndent(user, "", " ")
fmt.Println(string(jsonData))
// Unmarshal from JSON
var newUser User
json.Unmarshal(jsonData, &newUser)
}
Logging
| Library | Command | Purpose |
|---|
| logrus | go get -u github.com/sirupsen/logrus | Structured logging |
| zap | go get -u go.uber.org/zap | Fast structured logging |
| log/slog | Built-in (1.21+) | Standard structured logging |
| zerolog | go get -u github.com/rs/zerolog | Zero-allocation JSON logger |
Logrus Example
import log "github.com/sirupsen/logrus"
func main() {
log.SetFormatter(&log.JSONFormatter{})
log.SetLevel(log.InfoLevel)
log.WithFields(log.Fields{
"user": "john",
"id": 123,
}).Info("User logged in")
log.Error("An error occurred")
}
Concurrency & Async
| Library | Command | Purpose |
|---|
| errgroup | Built-in | Goroutine synchronization |
| sync | Built-in | Synchronization primitives |
| context | Built-in | Cancellation and deadlines |
| Go-routines | Built-in | Lightweight concurrency |
Goroutine Example
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
results := make(chan string)
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
results <- fmt.Sprintf("Task %d done", id)
}(i)
}
go func() {
wg.Wait()
close(results)
}()
for msg := range results {
fmt.Println(msg)
}
}
HTTP Clients
| Library | Command | Purpose |
|---|
| net/http | Built-in | Standard HTTP client/server |
| resty | go get -u github.com/go-resty/resty/v2 | HTTP client with retries |
| Uber Dig | go get -u go.uber.org/dig | Dependency injection |
| grpc | go get -u google.golang.org/grpc | RPC framework |
HTTP Client Request
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
resp, err := http.Get("https://api.github.com/users/golang")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
Cryptography
| Library | Command | Purpose |
|---|
| crypto | Built-in | Cryptographic functions |
| bcrypt | go get -u golang.org/x/crypto/bcrypt | Password hashing |
| jwt-go | go get -u github.com/golang-jwt/jwt/v5 | JWT token handling |
| argon2 | Built-in | Password hashing algorithm |
JWT Example
import jwt "github.com/golang-jwt/jwt/v5"
var mySigningKey = []byte("secret")
func main() {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "1234567890",
"name": "John Doe",
})
tokenString, _ := token.SignedString(mySigningKey)
println(tokenString)
}
Dependency Injection
| Library | Command | Purpose |
|---|
| Wire | go install github.com/google/wire/cmd/wire@latest | Compile-time DI |
| Dig | go get -u go.uber.org/dig | Runtime DI container |
| Fx | go get -u go.uber.org/fx | Application framework |
Validation
| Library | Command | Purpose |
|---|
| validator | go get -u github.com/go-playground/validator/v10 | Data validation |
| OZZO | go get -u github.com/go-ozzo/ozzo-validation/v4 | Validation rules engine |
Validator Example
import "github.com/go-playground/validator/v10"
type User struct {
Email string `validate:"required,email"`
Age int `validate:"required,min=18"`
}
func main() {
validate := validator.New()
user := User{Email: "john@example.com", Age: 25}
err := validate.Struct(user)
}
Useful Commands
Dependency Management
# Download dependencies
go mod download
# Verify dependencies
go mod verify
# Tidy up dependencies
go mod tidy
# Display dependency graph
go mod graph
# Update specific package
go get -u github.com/package@v1.2.3
# View available versions
go list -m -versions github.com/package
Build & Run
# Run code
go run main.go
# Build binary
go build -o myapp
# Build with optimization
go build -ldflags="-s -w" -o myapp
# Cross-compile for Linux
GOOS=linux GOARCH=amd64 go build -o myapp
# Cross-compile for Windows
GOOS=windows GOARCH=amd64 go build -o myapp.exe
# Format code
go fmt ./...
# Lint code
golangci-lint run
Testing & Coverage
# Run tests
go test ./...
# Run tests with verbose output
go test -v ./...
# Run specific test
go test -run TestAddFunc ./...
# Generate coverage report
go test -cover ./...
# Generate coverage file
go test -coverprofile=coverage.out ./...
# View coverage in browser
go tool cover -html=coverage.out
# Run benchmarks
go test -bench=. -benchmem ./...
# Profile CPU
go test -cpuprofile=cpu.prof -bench=.
# Analyze profile
go tool pprof cpu.prof
# Memory profiling
go test -memprofile=mem.prof -bench=.
Project Structure
myproject/
├── main.go
├── go.mod
├── go.sum
├── cmd/
│ └── myapp/
│ └── main.go
├── internal/
│ ├── handler/
│ │ └── user.go
│ ├── service/
│ │ └── user.go
│ └── repository/
│ └── user.go
├── pkg/
│ └── utils/
│ └── helpers.go
└── test/
└── integration_test.go
Best Practices
- Use
go mod for dependency management
- Follow the Standard Go Project Layout
- Write table-driven tests
- Use interfaces for decoupling
- Implement proper error handling with custom error types
- Use contexts for cancellation and timeouts
- Write idiomatic Go code
- Use gofmt and golangci-lint
- Keep packages small and focused
- Document exported functions
- Use semantic versioning for releases
Last updated: 2026-03-30