Table of Contents

HTTP Server (net/http)

What is it?

An HTTP server is a program that listens on a network address (host:port) and serves HTTP requests by calling a handler.

In Go, the standard library package `net/http` provides everything you need to build a basic server.

What is it used for?

Core building blocks

Minimal server (Hello + health)

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))
}

Production notes (important)

For production, you often use `http.Server` to set timeouts and graceful shutdown.

Example fields:

Hard words (English)