### Build a Simple Web Server with Gin and Go Modules (Go and Bash) Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Demonstrates how to build a basic web server using the Gin framework and Go modules. It shows how to import necessary packages like 'gin' and 'godotenv', handle HTTP requests, load environment variables, and run the server. The example also includes commands to install dependencies and test the server. ```go // server.go package main import ( "fmt" "net/http" "os" "github.com/gin-gonic/gin" "github.com/joho/godotenv" ) func main() { // Load environment variables if err := godotenv.Load(); err != nil { fmt.Fprintf(os.Stderr, "Error loading .env file: %v\n", err) os.Exit(1) } // Create router router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "pong", }) }) port := os.Getenv("PORT") if port == "" { port = "8080" } if err := router.Run(":" + port); err != nil { fmt.Fprintf(os.Stderr, "Server failed to start: %v\n", err) os.Exit(1) } } ``` ```bash # Install dependencies go get github.com/gin-gonic/gin go get github.com/joho/godotenv # Run the server PORT=3000 go run server.go # Test the endpoint curl http://localhost:3000/ping # Output: {"message":"pong"} ``` -------------------------------- ### Install Go from Binary Distribution (Bash) Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Installs Go by downloading the latest binary distribution, extracting it to /usr/local, and configuring the PATH environment variable. It also sets up the Go workspace directory. This method is suitable for most users and platforms. ```bash # Download the latest Go binary for your platform wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz # Extract to /usr/local sudo rm -rf /usr/local/go sudo tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz # Add Go to PATH (add to ~/.profile or ~/.bashrc) export PATH=$PATH:/usr/local/go/bin # Verify installation go version # Output: go version go1.21.5 linux/amd64 # Set up workspace mkdir -p ~/go/{bin,src,pkg} export GOPATH=$HOME/go export PATH=$PATH:$GOPATH/bin ``` -------------------------------- ### Go Command Line for Testing Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Provides examples of using the `go test` command-line tool to run unit tests, get verbose output, check code coverage, and run benchmarks. These commands are executed in a Go environment. ```bash # Run tests go test ./... # Output: ok example.com/myproject/math 0.002s # Run with verbose output go test -v ./... # Output: # === RUN TestAdd # === RUN TestAdd/positive_numbers # === RUN TestAdd/negative_numbers # === RUN TestAdd/mixed_signs # === RUN TestAdd/zeros # --- PASS: TestAdd (0.00s) # === RUN TestMultiply # --- PASS: TestMultiply (0.00s) # PASS # ok example.com/myproject/math 0.002s # Run with coverage go test -cover ./... # Output: ok example.com/myproject/math 0.002s coverage: 100.0% of statements # Generate coverage report go test -coverprofile=coverage.out ./... go tool cover -html=coverage.out -o coverage.html # Run benchmarks go test -bench=. ./... # Output: # BenchmarkAdd-8 1000000000 0.2537 ns/op # PASS ``` -------------------------------- ### Create and Run Hello World Program (Go and Bash) Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Demonstrates the basic structure of a Go program by creating a 'Hello, World!' application. It shows how to run the program directly using 'go run', build an executable with 'go build', and install it to the GOPATH bin directory with 'go install'. ```go // main.go package main import "fmt" func main() { fmt.Println("Hello, World!") } ``` ```bash # Run directly go run main.go # Output: Hello, World! # Build executable go build -o hello main.go ./hello # Output: Hello, World! # Build and install to $GOPATH/bin go install ``` -------------------------------- ### Go API Server Installation and Testing with Bash Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Provides bash commands to install the Go Gorilla Mux dependency, run the Go API server, and test its endpoints using curl. This helps in setting up and verifying the functionality of the REST API. ```bash # Install dependency go get -u github.com/gorilla/mux # Run server go run api_server.go # Test endpoints curl -X POST http://localhost:8080/users \ -H "Content-Type: application/json" \ -d '{"id":"1","name":"John Doe","email":"john@example.com"}' # Output: {"id":"1","name":"John Doe","email":"john@example.com"} curl http://localhost:8080/users # Output: [{"id":"1","name":"John Doe","email":"john@example.com"}] curl http://localhost:8080/users/1 # Output: {"id":"1","name":"John Doe","email":"john@example.com"} ``` -------------------------------- ### Build Go from Source (Bash) Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Builds the Go programming language from its source code, allowing for custom configurations or installation on unsupported platforms. It involves cloning the repository, checking out a specific version, bootstrapping the toolchain, and setting environment variables for the installation. ```bash # Clone the Go repository git clone https://go.googlesource.com/go cd go git checkout go1.21.5 # Bootstrap from existing Go installation cd src ./all.bash # Expected output includes: # Building Go cmd/dist using /usr/local/go # Building Go toolchain1 using /usr/local/go # Building Go bootstrap cmd/go (go_bootstrap) using Go toolchain1 # Building Go toolchain2 using go_bootstrap # Building Go toolchain3 using go_bootstrap # ... # ALL TESTS PASSED # Set GOROOT to custom installation export GOROOT=$HOME/go export PATH=$GOROOT/bin:$PATH ``` -------------------------------- ### Building and Contributing to Go from Source Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Guides users on how to clone the Go source repository, build the Go toolchain from source using `./all.bash`, make modifications, rebuild, and run tests. It also covers the process of submitting contributions using Gerrit for code review. ```bash # Clone the repository git clone https://go.googlesource.com/go cd go # Checkout the latest release branch git checkout release-branch.go1.21 # Build Go toolchain cd src ./all.bash # Expected output ends with: # ALL TESTS PASSED # # --- # Installed Go for linux/amd64 in /home/user/go # Installed commands in /home/user/go/bin # Make a change and rebuild cd .. # Edit files... cd src ./make.bash # Run tests ./run.bash # Run specific tests go test -run=TestSomething ./... ``` ```bash # Install Gerrit code review tool go install golang.org/x/review/git-codereview@latest # Configure git for Gerrit git config --global user.email "you@example.com" git codereview change # Create a new branch git checkout -b myfeature # Make changes and commit git add . git commit -m "pkg/feature: add new functionality This change adds X to improve Y by doing Z. Fixes #12345" # Run tests before submitting ./all.bash # Submit for review git codereview mail # Expected output: # remote: Processing changes: refs: 1, new: 1, done # remote: ``` -------------------------------- ### Go Unit Testing and Benchmarking Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Demonstrates how to write unit tests and benchmarks for Go functions using the built-in testing package. It includes examples of table-driven tests and running tests with different flags for verbosity and coverage. Assumes Go environment is set up. ```go // math.go package math func Add(a, b int) int { return a + b } func Multiply(a, b int) int { return a * b } ``` ```go // math_test.go package math import "testing" func TestAdd(t *testing.T) { tests := []struct { name string a, b int expected int }{ {"positive numbers", 2, 3, 5}, {"negative numbers", -2, -3, -5}, {"mixed signs", -2, 3, 1}, {"zeros", 0, 0, 0}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := Add(tt.a, tt.b) if result != tt.expected { t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected) } }) } } func TestMultiply(t *testing.T) { result := Multiply(3, 4) if result != 12 { t.Errorf("Multiply(3, 4) = %d; want 12", result) } } func BenchmarkAdd(b *testing.B) { for i := 0; i < b.N; i++ { Add(1, 2) } } ``` -------------------------------- ### Initialize and Manage Go Modules (Bash) Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Initializes a new Go module for dependency management in a project. It covers creating a project directory, initializing the module with 'go mod init', adding dependencies using 'go get', and maintaining the module's integrity with 'go mod tidy' and 'go mod vendor'. ```bash # Create new project directory mkdir myproject cd myproject # Initialize Go module go mod init example.com/myproject # Creates go.mod file # go.mod content: # module example.com/myproject # # go 1.21 # Add dependency go get github.com/gin-gonic/gin@v1.9.1 # go.mod now includes: # module example.com/myproject # # go 1.21 # # require github.com/gin-gonic/gin v1.9.1 # # require ( # github.com/bytedance/sonic v1.9.1 // indirect # github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect # ... # ) # Tidy dependencies go mod tidy # Vendor dependencies go mod vendor ``` -------------------------------- ### Go Concurrency with Goroutines and Channels Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Illustrates concurrent programming in Go using goroutines for parallel execution and channels for safe communication between them. This example simulates a worker pool processing jobs and collecting results. Requires Go runtime. ```go // concurrent.go package main import ( "fmt" "sync" "time" ) func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) { defer wg.Done() for j := range jobs { fmt.Printf("Worker %d started job %d\n", id, j) time.Sleep(time.Second) // Simulate work results <- j * 2 fmt.Printf("Worker %d finished job %d\n", id, j) } } func main() { const numJobs = 5 const numWorkers = 3 jobs := make(chan int, numJobs) results := make(chan int, numJobs) var wg sync.WaitGroup // Start workers for w := 1; w <= numWorkers; w++ { wg.Add(1) go worker(w, jobs, results, &wg) } // Send jobs for j := 1; j <= numJobs; j++ { jobs <- j } close(jobs) // Wait for workers to finish go func() { wg.Wait() close(results) }() // Collect results for result := range results { fmt.Printf("Result: %d\n", result) } } ``` -------------------------------- ### Go Context for Cancellation Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Shows how to use Go's `context` package to manage request lifecycles and implement cancellation signals, particularly useful in concurrent operations. This example uses `context.WithTimeout` to demonstrate cancellation. Requires Go runtime. ```go // context_example.go package main import ( "context" "fmt" "time" ) func operation(ctx context.Context, duration time.Duration, name string) { select { case <-time.After(duration): fmt.Printf("%s completed\n", name) case <-ctx.Done(): fmt.Printf("%s cancelled: %v\n", name, ctx.Err()) } } func main() { // Context with timeout ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() go operation(ctx, 1*time.Second, "Operation 1") go operation(ctx, 3*time.Second, "Operation 2") time.Sleep(4 * time.Second) } ``` -------------------------------- ### Multi-Stage Docker Build for Go Applications Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Create efficient Docker images for Go applications using a multi-stage build process. This approach separates the build environment from the runtime environment, resulting in smaller, more secure final images. It includes instructions for building the Docker image and running the container. ```dockerfile # Dockerfile FROM golang:1.21-alpine AS builder WORKDIR /app # Copy dependency files COPY go.mod go.sum . RUN go mod download # Copy source code COPY . . # Build application RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-s -w" -o main . # Final stage FROM alpine:latest RUN apk --no-cache add ca-certificates WORKDIR /root/ # Copy binary from builder COPY --from=builder /app/main . EXPOSE 8080 CMD ["./main"] ``` ```bash # Build Docker image docker build -t myapp:latest . # Run container docker run -d -p 8080:8080 --name myapp-container myapp:latest # View logs docker logs myapp-container # Stop container docker stop myapp-container # Remove container docker rm myapp-container ``` -------------------------------- ### PostgreSQL Database Operations with Go Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Demonstrates how to connect to a PostgreSQL database using the `pq` driver, perform Create, Read, Update, and Delete (CRUD) operations, and handle potential errors. It includes Go code for table creation, insertion, querying single and multiple rows, updating records, and deleting records. ```go // database.go package main import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" ) type Product struct { ID int Name string Price float64 } func main() { connStr := "host=localhost port=5432 user=postgres password=secret dbname=mydb sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { log.Fatal(err) } defer db.Close() if err := db.Ping(); err != nil { log.Fatal(err) } // Create table _, err = db.Exec(` CREATE TABLE IF NOT EXISTS products ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, price DECIMAL(10,2) NOT NULL ) `) if err != nil { log.Fatal(err) } // Insert result, err := db.Exec("INSERT INTO products (name, price) VALUES ($1, $2)", "Laptop", 999.99) if err != nil { log.Fatal(err) } id, _ := result.LastInsertId() fmt.Printf("Inserted product with ID: %d\n", id) // Query single row var product Product err = db.QueryRow("SELECT id, name, price FROM products WHERE id = $1", 1).Scan(&product.ID, &product.Name, &product.Price) if err != nil { log.Fatal(err) } fmt.Printf("Product: %+v\n", product) // Output: Product: {ID:1 Name:Laptop Price:999.99} // Query multiple rows rows, err := db.Query("SELECT id, name, price FROM products WHERE price > $1", 500.00) if err != nil { log.Fatal(err) } defer rows.Close() var products []Product for rows.Next() { var p Product if err := rows.Scan(&p.ID, &p.Name, &p.Price); err != nil { log.Fatal(err) } products = append(products, p) } fmt.Printf("Products: %+v\n", products) // Update _, err = db.Exec("UPDATE products SET price = $1 WHERE id = $2", 899.99, 1) if err != nil { log.Fatal(err) } // Delete _, err = db.Exec("DELETE FROM products WHERE id = $1", 1) if err != nil { log.Fatal(err) } } ``` ```bash # Install PostgreSQL driver go get github.com/lib/pq # Run the program go run database.go ``` -------------------------------- ### Cross-Platform Go Binary Builds Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Learn how to compile Go applications for various operating systems and architectures using the `go build` command with environment variables like `GOOS` and `GOARCH`. This section also covers applying build flags for optimizations and embedding version information. ```bash # Build for current platform go build -o myapp main.go # Build for Linux AMD64 GOOS=linux GOARCH=amd64 go build -o myapp-linux-amd64 main.go # Build for Windows AMD64 GOOS=windows GOARCH=amd64 go build -o myapp-windows-amd64.exe main.go # Build for macOS ARM64 (Apple Silicon) GOOS=darwin GOARCH=arm64 go build -o myapp-darwin-arm64 main.go # Build with optimizations and stripped symbols go build -ldflags="-s -w" -o myapp main.go # Build with version information VERSION=$(git describe --tags --always) go build -ldflags="-X main.version=${VERSION}" -o myapp main.go ``` -------------------------------- ### Go REST API Server with Gorilla Mux Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Implements a RESTful API server in Go using the Gorilla Mux router. It supports CRUD operations for users and includes logging middleware. Dependencies include the Gorilla Mux library. Inputs are JSON payloads for user creation, and outputs are JSON responses. It uses an in-memory map for data storage, so data is not persistent. ```go // api_server.go package main import ( "encoding/json" "fmt" "log" "net/http" "sync" "github.com/gorilla/mux" ) type User struct { ID string `json:"id"` Name string `json:"name"` Email string `json:"email"` } type Store struct { mu sync.RWMutex users map[string]User } func NewStore() *Store { return &Store{ users: make(map[string]User), } } func (s *Store) GetUser(id string) (User, bool) { s.mu.RLock() defer s.mu.RUnlock() user, ok := s.users[id] return user, ok } func (s *Store) CreateUser(user User) { s.mu.Lock() defer s.mu.Unlock() s.users[user.ID] = user } func (s *Store) GetAllUsers() []User { s.mu.RLock() defer s.mu.RUnlock() users := make([]User, 0, len(s.users)) for _, user := range s.users { users = append(users, user) } return users } func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("%s %s", r.Method, r.URL.Path) next.ServeHTTP(w, r) }) } func main() { store := NewStore() router := mux.NewRouter() router.Use(loggingMiddleware) router.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) { users := store.GetAllUsers() w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(users) }).Methods("GET") router.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) { var user User if err := json.NewDecoder(r.Body).Decode(&user); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } store.CreateUser(user) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(user) }).Methods("POST") router.HandleFunc("/users/{id}", func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) user, ok := store.GetUser(vars["id"]) if !ok { http.Error(w, "User not found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(user) }).Methods("GET") fmt.Println("Server starting on :8080") log.Fatal(http.ListenAndServe(":8080", router)) } ``` -------------------------------- ### User Management API Source: https://context7.com/context7/cs_opensource_google_go_go_master_doc/llms.txt Endpoints for managing user data, including creating users and retrieving user information. ```APIDOC ## GET /users ### Description Retrieves a list of all users. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **users** (array) - An array of user objects. - **id** (string) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json [ { "id": "1", "name": "John Doe", "email": "john@example.com" } ] ``` ## POST /users ### Description Creates a new user. ### Method POST ### Endpoint /users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (string) - Required - The unique identifier for the new user. - **name** (string) - Required - The name of the new user. - **email** (string) - Required - The email address of the new user. ### Request Example ```json { "id": "1", "name": "John Doe", "email": "john@example.com" } ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier for the created user. - **name** (string) - The name of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "1", "name": "John Doe", "email": "john@example.com" } ``` ## GET /users/{id} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": "1", "name": "John Doe", "email": "john@example.com" } ``` #### Error Response (404 Not Found) If the user with the specified ID is not found. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.