Courses/Go/Building Web Services

    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

    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

    Try it Yourself »
    JavaScript
    // 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

    Try it Yourself »
    JavaScript
    // 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

    Try it Yourself »
    JavaScript
    // 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

    Try it Yourself »
    JavaScript
    // 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

    ⚠️
    Not setting Content-Type — Always set w.Header().Set("Content-Type", "application/json") for JSON APIs.
    ⚠️
    Ignoring request body close — Always defer r.Body.Close() after reading the body.
    💡
    Pro Tip: Start with the standard library. Only add a framework when you need features it doesn't provide (like route groups or parameter validation).

    📋 Quick Reference

    PatternGo Syntax
    Handlerhttp.HandleFunc("/path", fn)
    Start serverhttp.ListenAndServe(":8080", nil)
    JSON responsejson.NewEncoder(w).Encode(data)
    Path paramr.PathValue("id")
    Middlewarefunc(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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service