Salta ai contenuti

Go Commands

Go is a statically typed, compiled programming language designed for simplicity, concurrency, and performance.

Installation

Linux

# Download latest Go release
wget https://go.dev/dl/go1.21.0.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz

# Add Go to PATH
export PATH=$PATH:/usr/local/go/bin
echo "export PATH=$PATH:/usr/local/go/bin" >> ~/.bashrc
source ~/.bashrc

# Verify installation
go version

macOS

# Homebrew installation
brew install go

# Or download from go.dev
curl -L https://go.dev/dl/go1.21.0.darwin-amd64.tar.gz -o go.tar.gz
tar -C /usr/local -xzf go.tar.gz

# Verify
go version

Windows

# Chocolatey installation
choco install golang

# Or download MSI installer from https://go.dev/dl/
# Then verify in PowerShell
go version

Basic Commands

CommandDescription
go versionDisplay Go version
go envShow Go environment variables
go helpDisplay help information
go new <module>Create new module
go run <file.go>Compile and run program
go build <file.go>Compile to binary
go test ./...Run tests in current directory
go fmt ./...Format code
go vet ./...Analyze code for bugs

Project Setup

# Create new Go module
go mod init github.com/username/project

# Create project structure
mkdir -p {cmd,pkg,internal,tests}
touch main.go

# Initialize Go module with go.mod and go.sum
cat > go.mod << EOF
module github.com/username/project

go 1.21
EOF

Go Modules

# Initialize a new module
go mod init github.com/username/myapp

# Add dependencies
go get github.com/gorilla/mux@latest
go get -u github.com/spf13/cobra

# List all dependencies
go mod graph

# Tidy dependencies (remove unused)
go mod tidy

# Download dependencies
go mod download

# Vendor dependencies
go mod vendor

# Verify module integrity
go mod verify

# View dependency tree
go mod why -m github.com/gorilla/mux

Building and Running

# Run program directly
go run main.go

# Run with arguments
go run main.go -flag value arg1 arg2

# Build binary
go build -o myapp main.go

# Build with version info
go build -ldflags "-X main.Version=1.0.0" -o myapp main.go

# Cross-compile for Linux
GOOS=linux GOARCH=amd64 go build -o myapp main.go

# Cross-compile for Windows
GOOS=windows GOARCH=amd64 go build -o myapp.exe main.go

# Cross-compile for macOS
GOOS=darwin GOARCH=amd64 go build -o myapp main.go

# Build with optimizations
go build -ldflags "-s -w" -o myapp main.go

Testing

# Run all tests
go test ./...

# Run tests with verbose output
go test -v ./...

# Run specific test
go test -run TestFunctionName ./...

# Run tests with coverage
go test -cover ./...

# Generate coverage report
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

# Run tests with timeout
go test -timeout 10s ./...

# Run benchmark tests
go test -bench=. -benchmem ./...

# Run tests in parallel
go test -parallel 4 ./...

# Run with race detector
go test -race ./...

Code Quality

# Format code
go fmt ./...

# Format and check with gofmt
gofmt -w .

# Run vet analysis
go vet ./...

# Check code style (requires golangci-lint)
golangci-lint run ./...

# Run staticcheck (requires staticcheck)
staticcheck ./...

# Check for inefficient code
go test -bench . -benchmem

# Generate documentation
godoc -http=:6060
# Visit http://localhost:6060

Basic Program Structure

package main

import (
    "fmt"
    "log"
)

func main() {
    fmt.Println("Hello, World!")
}

Functions and Types

// Function declaration
func greet(name string) string {
    return "Hello, " + name
}

// Multiple return values
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

// Struct definition
type Person struct {
    Name string
    Age  int
}

// Method on struct
func (p Person) Greet() string {
    return fmt.Sprintf("Hello, I'm %s", p.Name)
}

// Interface definition
type Writer interface {
    Write(p []byte) (n int, err error)
}

Concurrency

// Goroutine
go func() {
    fmt.Println("Running concurrently")
}()

// Channels
ch := make(chan string)
go func() {
    ch <- "message"
}()
msg := <-ch

// Buffered channel
ch := make(chan int, 10)

// Select statement
select {
case msg := <-ch1:
    fmt.Println("Received from ch1:", msg)
case msg := <-ch2:
    fmt.Println("Received from ch2:", msg)
default:
    fmt.Println("No message received")
}

// WaitGroup for synchronization
var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    // do work
}()
wg.Wait()

Error Handling

// Check error
result, err := someFunction()
if err != nil {
    log.Fatal(err)
}

// Custom error
type MyError struct {
    msg string
}

func (e MyError) Error() string {
    return e.msg
}

// Error wrapping (Go 1.13+)
err := fmt.Errorf("operation failed: %w", originalErr)

// Error unwrapping
if errors.Is(err, originalErr) {
    // handle specific error
}

Common Packages

fmt

// Formatting and printing
fmt.Println("Hello")
fmt.Printf("%s %d\n", "Count:", 5)
output := fmt.Sprintf("Formatted: %v", value)

strings

// String operations
strings.Contains("hello", "ell")          // true
strings.ToUpper("hello")                  // "HELLO"
strings.Split("a,b,c", ",")               // ["a", "b", "c"]
strings.TrimSpace("  hello  ")            // "hello"
strings.Replace("foo foo", "foo", "bar", 2)  // "bar bar"

net/http

// HTTP client
resp, err := http.Get("https://example.com")
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

body, _ := ioutil.ReadAll(resp.Body)

// HTTP server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
})
http.ListenAndServe(":8080", nil)

encoding/json

// Marshal to JSON
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

user := User{"John", 30}
jsonData, _ := json.Marshal(user)

// Unmarshal from JSON
var user User
json.Unmarshal(jsonData, &user)

// Pretty print JSON
prettyJSON, _ := json.MarshalIndent(user, "", "  ")

database/sql

// Open database
db, err := sql.Open("postgres", "postgres://user:pass@localhost/dbname")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Query
rows, _ := db.Query("SELECT id, name FROM users WHERE age > ?", 18)
defer rows.Close()

for rows.Next() {
    var id int
    var name string
    rows.Scan(&id, &name)
}

// Execute
result, _ := db.Exec("INSERT INTO users (name) VALUES (?)", "John")
lastID, _ := result.LastInsertId()

Package Management

# Get package documentation
go doc fmt.Println

# Search for packages
go get golang.org/x/tools/cmd/goimports

# Update all dependencies
go get -u ./...

# Clean cache
go clean -cache

# List outdated packages
go list -u -m all

# Get specific version
go get github.com/gorilla/mux@v1.8.0

# Get latest pre-release
go get github.com/lib/pq@latest

Debugging

# Debug with Delve
dlv debug
dlv debug -- -flag value

# Debug with breakpoint
(dlv) break main.main
(dlv) continue
(dlv) next
(dlv) print variable

# Profiling
go test -cpuprofile=cpu.prof ./...
go test -memprofile=mem.prof ./...
go tool pprof cpu.prof

# Trace execution
go test -trace=trace.out ./...
go tool trace trace.out

Environment Variables

VariableDescription
GOROOTGo installation directory
GOPATHWorkspace directory (less used in Go 1.11+)
GOOSTarget operating system
GOARCHTarget architecture
GO111MODULEEnable module mode (auto in Go 1.11+)
GOPROXYModule proxy URL
GOSUMDBChecksum database
CGO_ENABLEDEnable cgo (0 or 1)

Best Practices

  • Use interfaces for abstraction and testing
  • Leverage goroutines for concurrent operations
  • Handle errors explicitly
  • Keep packages focused and organized
  • Use meaningful variable names
  • Write table-driven tests
  • Document exported functions with comments
  • Use modules for dependency management
  • Run gofmt and vet before committing
  • Write benchmarks for performance-critical code

Useful Tools

# golint (code style linter)
go install golang.org/x/lint/golint@latest
golint ./...

# goimports (manage imports)
go install golang.org/x/tools/cmd/goimports@latest
goimports -w .

# staticcheck (advanced analysis)
go install honnef.co/go/tools/cmd/staticcheck@latest
staticcheck ./...

# golangci-lint (all-in-one linter)
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
golangci-lint run

# delve (debugger)
go install github.com/go-delve/delve/cmd/dlv@latest
dlv debug

Resources


Last updated: 2026-03-30|Go 1.21+