net/http
net/http is the standard library's HTTP client and server. http.ListenAndServe runs a server. http.Get and http.Client make requests. Handlers are http.Handler.
Detailed Explanation
You do not need a framework to serve HTTP in Go. http.HandleFunc("GET /health", fn) plus http.ListenAndServe(":8080", nil) is a server. The nil handler means the default ServeMux. Passing your own mux (or a middleware stack) is the usual production form: ListenAndServe(addr, handler).
The client. http.Get uses http.DefaultClient, which has no timeout. Production code uses &http.Client{Timeout: 10 * time.Second} or a client with a custom Transport. Always defer resp.Body.Close() after a successful Do/Get/Post, including when you do not read the body — otherwise connections leak from the pool.
Request and response. *http.Request holds method, URL, headers, body, and Context(). ResponseWriter is how a handler writes status and body. The server sets Request.Context() to a context cancelled when the client goes away.
HTTP/1.1 and HTTP/2. The server speaks both when TLS is configured (ListenAndServeTLS). Transport supports HTTP/2 by default for HTTPS.
What it costs. net/http is enough for most APIs. Frameworks add routing sugar and middleware stacks; they still sit on this package. The cost you must not skip is timeouts (client and server ReadHeaderTimeout) and closing bodies.
Code Examples
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ok")
})
http.ListenAndServe(":8080", nil)
}func fetch(url string) error {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = io.Copy(io.Discard, resp.Body)
return err
}Common Gotchas
`DefaultClient` has no timeout
a hung peer blocks a goroutine forever.
`ListenAndServe` returning `nil` does not happen on success
it blocks; a return is an error (except `ErrServerClosed` after `Shutdown`).
Go 1.22+ mux patterns include the method
`"GET /health"` is not matched by `POST`.
Forgetting `Body.Close()` on the client leaks file descriptors and pool slots
Forgetting `Body.Close()` on the client leaks file descriptors and pool slots