Loading...
Loading...
Master building scalable, secure RESTful APIs in Go 1.22+ using only the standard net/http library and enhanced ServeMux. Step-by-step planning, code examples for routing, validation, middleware, and testing.
## Overview of Go Standard Library API Development
Develop high-performance REST APIs exclusively with Go's `net/http` package and the upgraded ServeMux from Go 1.22+. Focus on idiomatic code that's secure, concurrent, and maintainable. Always plan meticulously before coding.
## Step 1: Detailed API Planning
Before writing code, outline the API structure:
1. Identify endpoints (e.g., `/users/{id}` for GET/PUT/DELETE, `/users` for POST).
2. Define request/response schemas (JSON).
3. Map data flow: request parsing → validation → business logic → response.
4. Consider middleware for auth/logging.
**Pseudocode Example:**
```
Plan:
- GET /users → list users (paginated)
- POST /users → create user (validate JSON body)
- GET /users/{id} → fetch user (wildcard route)
Data flow:
Parse r.Body → Validate fields → Query DB → Marshal JSON → w.Write
Error: 400 Bad Request on invalid input, 404 Not Found
```
Confirm plan with user, then implement.
## Step 2: Routing with ServeMux (Go 1.22+)
Use `http.NewServeMux()` for pattern matching, wildcards (`*`), and regex (`{id:\d+}`).
**Practical Code Example:**
```go
import (
"net/http"
"log"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /users", listUsers)
mux.HandleFunc("POST /users", createUser)
mux.HandleFunc("GET /users/{id:", getUser) // Wildcard
mux.HandleFunc(http.MethodGet, "/users/{id:\d+}", getUser) // Method + regex
http.ListenAndServe(":8080", mux)
}
```
## Step 3: Handler Functions and JSON Responses
Handlers: `func(http.ResponseWriter, *http.Request)`. Use `json.NewEncoder` for responses.
**Practical Code Example:**
```go
import (
"encoding/json"
"net/http"
)
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
func getUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") // New in 1.22
user := User{ID: id, Name: "John"}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
```
## Step 4: Input Validation and Error Handling
Validate with custom funcs. Return proper status codes.
**Practical Code Example:**
```go
import (
"encoding/json"
"fmt"
)
func createUser(w http.ResponseWriter, r *http.Request) {
var u User
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
if u.Name == "" {
http.Error(w, "Name required", http.StatusBadRequest)
return
}
// Save user...
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(u)
}
```
## Step 5: Middleware for Logging and Auth
Chain handlers with custom middleware.
**Practical Code Example:**
```go
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.Path)
next(w, r)
}
}
// Usage
mux.HandleFunc("GET /users", loggingMiddleware(listUsers))
```
For auth: Check `r.Header.Get("Authorization")`.
## Step 6: Concurrency and Logging
Use goroutines for I/O. Log with `log/slog` (Go 1.21+).
**Example:**
```go
go func() { /* background task */ }()
log.Printf("Request handled")
```
## Step 7: Testing Endpoints
Use `net/http/httptest`.
**Test Example:**
```go
import "testing"
func TestGetUser(t *testing.T) {
req := httptest.NewRequest("GET", "/users/123", nil)
rw := httptest.NewRecorder()
getUser(rw, req)
// Assert rw.Code, body
}
```
## Security and Best Practices
- Rate limit with custom token bucket.
- No placeholders; full implementations.
- Prioritize HTTPS, input sanitization, CORS if needed.
- Scale with Go routines, context timeouts.Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.
Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.
This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.
Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.
Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.
Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.