Go Reference ยท Networking and the Web
The Go net/http package
Overview of Go's net/http package: making requests, writing servers, handlers, ServeMux routing, status codes, headers, cookies, file serving and testing.
net/http is Go's complete HTTP implementation: a client for calling other services and a server for answering requests, both production-grade and used directly in many large systems. It supports HTTP/1.1 and HTTP/2 (HTTP/2 over TLS is automatic), keep-alive connection reuse, cookies, redirects, multipart bodies and streaming.
Most of the package revolves around three types: Request (what was sent), ResponseWriter (how you answer) and Handler (code that turns one into the other). Client side, Client sends a Request and gives back a Response.
resp, err := http.Get("https://example.com/")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
The package is large. This table groups its main pieces; each has its own page.
| Piece | Purpose |
|---|---|
http.Get(), Post, Head, PostForm |
One-line requests using DefaultClient. |
http.Client |
Timeouts, redirects, cookies and transports. |
http.Request, NewRequestWithContext |
A request received by a server or built by a client. |
http.ResponseWriter |
How a handler writes the status, headers and body. |
http.Handler, HandlerFunc |
The interface that serves requests. |
http.HandleFunc(), http.ServeMux |
Registering handlers and routing by method and path. |
http.Server, ListenAndServe |
Running a server with timeouts and graceful shutdown. |
http.Error, NotFound, Redirect, ServeFile, FileServer, MaxBytesReader, TimeoutHandler, StripPrefix |
Helpers for common handler jobs. |
http.Cookie, SetCookie |
Reading and setting cookies. |
http.StatusOK ... , StatusText, MethodGet ... |
Constants for status codes and methods. |
http.NewResponseController, Flusher, Hijacker |
Per-request control, flushing and taking over the connection. |
net/http/httptest |
Testing handlers and clients without a real network. |
Errors and edge cases:
- A client call returns an error for network problems and timeouts, not for 4xx and 5xx statuses. Check
resp.StatusCodeyourself. ListenAndServereturnshttp.ErrServerClosedafter a graceful shutdown. That is expected, not a failure.- Writing a header after the body has started has no effect; the first
Writesends200 OKif you have not calledWriteHeader.
Usage notes
- Always close response bodies (
defer resp.Body.Close()) and read them to the end when you want the connection reused. - The defaults are for demos.
http.DefaultClienthas no timeout, andhttp.ListenAndServehas none either. Production code uses its ownhttp.Clientandhttp.Serverwith timeouts. - Routing: since Go 1.22,
ServeMuxpatterns can include a method and wildcards, such asGET /items/{id}. When compiling a single file without ago.mod, add//go:debug httpmuxgo121=0to enable this. - Middleware is just a function that takes a
Handlerand returns aHandler. - Request context:
r.Context()is canceled when the client disconnects. Pass it to database and downstream calls. - Body limits: wrap request bodies in
http.MaxBytesReaderbefore decoding untrusted JSON or forms. - Third-party routers are optional. The standard
ServeMuxis enough for most services. - HTTP/3 is not part of the standard library.