Lesson 7 • Advanced
Building Web Services 🐹
Create HTTP servers, REST APIs, and middleware using Go's powerful standard library — no external framework needed.
What You'll Learn in This Lesson
- • Creating HTTP servers with
net/http - • Building REST APIs with JSON responses
- • Middleware pattern for logging, auth, CORS
- • Go 1.22+ routing with method and path params
- • Popular Go web frameworks overview
go mod init myapi && go run main.go.net/http is like a post office. Handlers are the mailboxes (each route has its own). Middleware is the sorting machine — every letter passes through it (logging, security checks) before reaching the right mailbox.1️⃣ HTTP Server Basics
Go's standard library includes a production-grade HTTP server. Just define handlers and call http.ListenAndServe. No framework needed — this is what powers many high-traffic services.
Try It: HTTP Server
Create a basic web server with route handlers
// HTTP Server with net/http
console.log("=== Go's Built-in HTTP Server ===");
console.log("Go's standard library includes a production-ready HTTP server.");
console.log("No external framework needed!");
console.log();
console.log("package main");
console.log();
console.log('import (');
console.log(' "fmt"');
console.log(' "net/http"');
console.log(')');
console.log();
console.log("func helloHandler(w http.ResponseWriter, r *http.Request) {");
console.log(' fmt.Fprintf(w, "Hello, %s!",
...2️⃣ REST API with JSON
Use struct tags for JSON serialization and json.NewEncoder to write responses. Handle different HTTP methods with a switch statement in your handler.
Try It: REST API
Build a CRUD API with JSON responses
// Building a REST API
console.log("=== REST API with JSON ===");
console.log();
console.log("type User struct {");
console.log(' ID int `json:"id"`');
console.log(' Name string `json:"name"`');
console.log(' Email string `json:"email"`');
console.log("}");
console.log();
console.log("func getUsersHandler(w http.ResponseWriter, r *http.Request) {");
console.log(' users := []User{');
console.log(' {ID: 1, Name: "Alice", Email: "alice@dev.com"},');
console.log('
...3️⃣ Middleware
Middleware wraps handlers to add cross-cutting concerns: logging, authentication, CORS, rate limiting. Chain them together for a clean separation of concerns.
Try It: Middleware
Logging, auth, and middleware chaining
// Middleware Pattern
console.log("=== What is Middleware? ===");
console.log("Middleware wraps handlers to add cross-cutting concerns:");
console.log("logging, auth, CORS, rate limiting, etc.");
console.log();
console.log("=== Logging Middleware ===");
console.log("func loggingMiddleware(next http.Handler) http.Handler {");
console.log(" return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {");
console.log(" start := time.Now()");
console.log(" next.ServeHTTP(w
...4️⃣ Modern Routing
Go 1.22 added method-based routing and path parameters to the standard library. For more features, popular frameworks like Chi and Gin build on the same patterns.
Try It: Routing
Go 1.22+ routing and framework comparison
// HTTP Router with Go 1.22+ (ServeMux)
console.log("=== Modern Routing (Go 1.22+) ===");
console.log("Go 1.22 added method-based routing and path parameters!");
console.log();
console.log("func main() {");
console.log(" mux := http.NewServeMux()");
console.log();
console.log(' mux.HandleFunc("GET /api/users", getUsers)');
console.log(' mux.HandleFunc("POST /api/users", createUser)');
console.log(' mux.HandleFunc("GET /api/users/{id}", getUser)');
console.log(' mux.HandleFunc("PU
...⚠️ Common Mistakes
w.Header().Set("Content-Type", "application/json") for JSON APIs.defer r.Body.Close() after reading the body.📋 Quick Reference
| Pattern | Go Syntax |
|---|---|
| Handler | http.HandleFunc("/path", fn) |
| Start server | http.ListenAndServe(":8080", nil) |
| JSON response | json.NewEncoder(w).Encode(data) |
| Path param | r.PathValue("id") |
| Middleware | func(next http.Handler) http.Handler |
🎉 Lesson Complete!
You can now build production web services in Go! Next, we'll learn how to write tests and benchmarks.
Sign up for free to track which lessons you've completed and get learning reminders.