HowtoGo
Home / Standard Library / The net/http Package
Standard Library

The net/http Package

net/http is a full HTTP client and server, no framework required.

Examples

Bare ListenAndServe sets no timeouts. Configure a *Server.

mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.Write([]byte("{\"status\":\"ok\"}"))
})

server := &http.Server{
    Addr:         ":8080",
    Handler:      mux,
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
    IdleTimeout:  120 * time.Second,
}
log.Fatal(server.ListenAndServe())
Output
$ curl localhost:8080/health
{"status":"ok"}

Functions

FunctionDescription
NewServeMux() *ServeMux
mux := http.NewServeMux()
Empty router. Register routes on the returned value.
ListenAndServe(addr string, handler Handler) error
Blocks. Error only on shutdown.
ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
http.ListenAndServeTLS(":443", crt, key, mux)
The same, over HTTPS.
Serve(l net.Listener, handler Handler) error
http.Serve(ln, mux)
Serves on a listener you opened yourself.
Error(w ResponseWriter, error string, code int)
Writes status and message, as plain text.
NotFound(w ResponseWriter, r *Request)
http.NotFound(w, r)
Writes a 404 with a plain body.
Redirect(w ResponseWriter, r *Request, url string, code int)
http.Redirect(w, r, "/login", 302)
Sets Location and writes the status.
SetCookie(w ResponseWriter, cookie *Cookie)
http.SetCookie(w, &http.Cookie{Name: "s", Value: v})
Adds one Set-Cookie header.
ServeFile(w ResponseWriter, r *Request, name string)
http.ServeFile(w, r, "./static/logo.png")
Sends one file, handling ranges and caching.
ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
http.ServeContent(w, r, "a.txt", t, bytes.NewReader(b))
ServeFile, for content that isn't a file.
FileServer(root FileSystem) Handler
http.Handle("/static/", h)
Serves a whole directory tree.
StripPrefix(prefix string, h Handler) Handler
http.StripPrefix("/static/", fs)
Trims the mux's prefix before the inner handler sees it.
MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
Caps how much of a body will be read.
DetectContentType(data []byte) string
ct := http.DetectContentType(b)
Sniffs a MIME type from the first 512 bytes.
StatusText(code int) string
http.StatusText(404)
The reason phrase, "Not Found".
Get(url string) (*Response, error)
resp, err := http.Get(u)
defer resp.Body.Close() once err is nil.
Post(url, contentType string, body io.Reader) (*Response, error)
resp, err := http.Post(u, "application/json", r)
A POST with a body you supply.
PostForm(url string, data url.Values) (*Response, error)
resp, err := http.PostForm(u, url.Values{"q": {"go"}})
A POST of form-encoded values.
NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
The request builder to reach for.
NewRequest(method, url string, body io.Reader) (*Request, error)
req, err := http.NewRequest("GET", u, nil)
The same, with no context attached.
ParseCookie(line string) ([]*Cookie, error)
cs, err := http.ParseCookie(raw)
Parses a raw Cookie header.

Types

Open a row for the type's full method set.

TypeDescription
type ServeMux struct4 methods
The router. Matches a request to a handler.
type Server struct8 methods
The server, with the timeouts ListenAndServe leaves unset.
type Request struct21 methods
The incoming request, or the outgoing one you build.
type ResponseWriter interface3 methods
How a handler answers. Three methods, in a fixed order.
type Handler interface1 method
One method. Everything that serves a request is one.
type HandlerFunc func(ResponseWriter, *Request)1 method
Turns a plain function into a Handler.
type Client struct6 methods
The other side. Set its Timeout.
type Response struct4 methods
What comes back. Close the Body.
type Header map[string][]string7 methods
The header map, on both a request and a response.
type Cookie struct2 methods
One cookie, going out or coming in.
type ResponseController struct5 methods
Reaches past the ResponseWriter interface, without a type assertion.
type Hijacker interface1 method
Type-assert w to get the raw connection.
type Flusher interface1 method
Sends buffered output without waiting for the handler to return.
type RoundTripper interface1 method
One request, one response, no redirects or cookies.
type CookieJar interface2 methods
Storage a Client keeps cookies in between calls.

Values

ValueDescription
StatusOK, StatusCreated, StatusNoContent int
w.WriteHeader(http.StatusCreated)
200, 201, 204.
StatusMovedPermanently, StatusFound, StatusSeeOther int
http.Redirect(w, r, "/", http.StatusSeeOther)
301, 302, 303.
StatusBadRequest, StatusUnauthorized, StatusForbidden, StatusNotFound int
http.Error(w, "no", http.StatusForbidden)
400, 401, 403, 404.
StatusMethodNotAllowed, StatusConflict, StatusUnprocessableEntity int
w.WriteHeader(http.StatusConflict)
405, 409, 422.
StatusTooManyRequests int
w.WriteHeader(http.StatusTooManyRequests)
429.
StatusInternalServerError, StatusServiceUnavailable int
http.Error(w, "server error", 500)
500, 503.
MethodGet, MethodPost, MethodPut, MethodPatch, MethodDelete string
http.NewRequest(http.MethodPost, u, body)
The method names, as strings.
DefaultClient *Client
http.DefaultClient.Do(req)
What http.Get uses. No timeout.
ErrServerClosed error
errors.Is(err, http.ErrServerClosed)
The server stopped on purpose.
ErrNoCookie error
errors.Is(err, http.ErrNoCookie)
The request had no cookie under that name.