Table of Contents

HTTP Server (net/http)

What is it?

An HTTP server is a program (service) that:

In Go, the standard library package `net/http` provides everything needed to build an HTTP server.

What is it used for?

Core building blocks

Minimal server (custom mux)

package main
 
import (
    "log"
    "net/http"
)
 
func main() {
    mux := http.NewServeMux()
 
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("hello"))
    })
 
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("ok"))
    })
 
    log.Println("listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

Common patterns

Production notes (important)

For production, prefer `http.Server{…}` with timeouts and graceful shutdown. Time-outs help protect against slow-client attacks and avoid hanging connections.

Hard words (English)