CodeNebula
Go📦Standard Libraryintermediate

net/http — HTTP Client and Server

Go · Standard Library · Run with go run

Explanation

`net/http` is a production-grade HTTP/1.1 and HTTP/2 library in the standard library. `http.ListenAndServe` starts a server; `http.HandleFunc` registers routes. The `http.Client` makes HTTP requests with full control over timeouts, redirects, and TLS. Always set timeouts on production clients — the zero-value `http.DefaultClient` has no timeouts.

Real-World Scenario

Microservices written in Go use `net/http` directly (no framework) for simple APIs. A service adds authentication middleware by wrapping `http.Handler` — the composition pattern means no magic, just function calls.

Quick Snippet

snippet.go
// Server
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    fmt.Fprintln(w, `{"status":"ok"}`)
})
log.Fatal(http.ListenAndServe(":8080", nil))

// Client with timeout (always set in production)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get("https://api.example.com/users")
if err != nil { return err }
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)

Full Example

http_server.go
// Compile: go run http_server.go
// Then: curl http://localhost:8080/health
// Output: {"status":"ok"}
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

type HealthResponse struct {
	Status    string    `json:"status"`
	Timestamp time.Time `json:"timestamp"`
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(HealthResponse{
		Status:    "ok",
		Timestamp: time.Now(),
	})
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
	if name == "" {
		name = "World"
	}
	fmt.Fprintf(w, "Hello, %s!\n", name)
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/health", healthHandler)
	mux.HandleFunc("/hello", helloHandler)

	server := &http.Server{
		Addr:         ":8080",
		Handler:      mux,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	log.Println("listening on :8080")
	log.Fatal(server.ListenAndServe())
}
Run command
go run http_server.go