Zum Inhalt springen

Awesome-Go Libraries

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

LibraryCommandPurpose
Gingo get -u github.com/gin-gonic/ginHigh-performance HTTP web framework
Echogo get -u github.com/labstack/echo/v4Minimalist web framework
Fibergo get -u github.com/gofiber/fiber/v2Express-inspired web framework
Chigo get -u github.com/go-chi/chi/v5Lightweight router for HTTP services
GORMgo get -u gorm.io/gormORM 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

LibraryCommandPurpose
GORMgo get -u gorm.io/gormObject-relational mapping
GORM PostgreSQLgo get -u gorm.io/driver/postgresPostgreSQL driver for GORM
GORM MySQLgo get -u gorm.io/driver/mysqlMySQL driver for GORM
database/sqlBuilt-inSQL database driver interface
sqlcgo install github.com/kyleconroy/sqlc/cmd/sqlc@latestGenerate 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{})
}

CLI Tools & Arguments

LibraryCommandPurpose
Cobrago get -u github.com/spf13/cobraCLI command framework
Vipergo get -u github.com/spf13/viperConfiguration management
urfave/cligo get -u github.com/urfave/cli/v2Command line app framework
Kingpingo get -u gopkg.in/alecthomas/kingpin.v2Command-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

LibraryCommandPurpose
Testifygo get -u github.com/stretchr/testifyTesting assertions and mocks
GoMockgo get -u github.com/golang/mock/gomockMock generation
Ginkgogo get -u github.com/onsi/ginkgo/v2BDD testing framework
Table-drivenBuilt-inPattern 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

LibraryCommandPurpose
encoding/jsonBuilt-inStandard JSON marshaling
json-iterator/gogo get -u github.com/json-iterator/goHigh-performance JSON parser
Protocol Buffersgo get -u github.com/protocolbuffers/protobuf-goEfficient serialization
MessagePackgo get -u github.com/msgpack/msgpack-goBinary 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

LibraryCommandPurpose
logrusgo get -u github.com/sirupsen/logrusStructured logging
zapgo get -u go.uber.org/zapFast structured logging
log/slogBuilt-in (1.21+)Standard structured logging
zerologgo get -u github.com/rs/zerologZero-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

LibraryCommandPurpose
errgroupBuilt-inGoroutine synchronization
syncBuilt-inSynchronization primitives
contextBuilt-inCancellation and deadlines
Go-routinesBuilt-inLightweight 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

LibraryCommandPurpose
net/httpBuilt-inStandard HTTP client/server
restygo get -u github.com/go-resty/resty/v2HTTP client with retries
Uber Diggo get -u go.uber.org/digDependency injection
grpcgo get -u google.golang.org/grpcRPC 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

LibraryCommandPurpose
cryptoBuilt-inCryptographic functions
bcryptgo get -u golang.org/x/crypto/bcryptPassword hashing
jwt-gogo get -u github.com/golang-jwt/jwt/v5JWT token handling
argon2Built-inPassword 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

LibraryCommandPurpose
Wirego install github.com/google/wire/cmd/wire@latestCompile-time DI
Diggo get -u go.uber.org/digRuntime DI container
Fxgo get -u go.uber.org/fxApplication framework

Validation

LibraryCommandPurpose
validatorgo get -u github.com/go-playground/validator/v10Data validation
OZZOgo get -u github.com/go-ozzo/ozzo-validation/v4Validation 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

Performance

# 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