net/http#
Client#
When making an HTTP call from your application to another HTTP service, use the NewRequestWithContext function to ensure that the request respects context cancellation and deadlines.
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)client := &http.Client{
Timeout: 30 * time.Second,
}
req, err := http.NewRequestWithContext(context.Background(),
http.MethodGet, "https://jsonplaceholder.typicode.com/todos/1", nil)
if err != nil {
panic(err)
}
req.Header.Add("X-My-Client", "Learning Go")
res, err := client.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
panic(fmt.Sprintf("unexpected status: got %v", res.Status))
}
fmt.Println(res.Header.Get("Content-Type"))
var data any
err = json.NewDecoder(res.Body).Decode(&data)Warning: Using
http.Get()and similar functions utilizeshttp.DefaultClient, which has no timeout. It is recommended to create and use a customhttp.Clientwith a timeout.
Server#
http.Handler and http.HandlerFunc#
http.HandlerInterfacetype Handler interface { ServeHTTP(ResponseWriter, *Request) }http.HandlerFuncAdaptertype HandlerFunc func(ResponseWriter, *Request)- The
HandlerFunctype is an adapter to allow the use of ordinary functions as HTTP handlers. Iffis a function with the appropriate signature,HandlerFunc(f)is aHandlerthat callsf.
- The
http.ResponseWriter#
type ResponseWriter interface {
Header() http.Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
}- These methods must be called in a specific order:
Header->WriteHeader->Write.
http.ResponseController#
- Since
http.ResponseWriteris an interface, adding new methods would break backward compatibility.http.ResponseControllerprovides access to extended functionality for the underlying concrete type.- If the wrapped
http.ResponseWriterdoes not support a specific method, it returnshttp.ErrNotSupportedvia type assertion.
- If the wrapped
func NewResponseController(rw ResponseWriter) *ResponseController: Creates aResponseControllerfrom anhttp.ResponseWriter.func (c *ResponseController) Flush() errorfunc (c *ResponseController) Hijack() (net.Conn, *bufio.ReadWriter, error)
http.Request#
func (r *Request) Context() context.Context: Returns the request’s context. To change the context, useWithContext.func (r *Request) WithContext(ctx context.Context) *Request: Returns a shallow copy ofrwith its context changed toctx.func (r *Request) ParseForm() error: Parses the raw query from the URL and updatesr.Form. For POST, PUT, and PATCH requests, it also reads the request body as a form and updatesr.PostFormandr.Form.func (r *Request) FormValue(key string) string: Returns the first value for the named component of the query.FormValuecallsParseFormif necessary.
http.Server#
s := http.Server{
Addr: ":8080",
ReadTimeout: 30 * time.Second,
WriteTimeout: 90 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: HelloHandler{},
}
err := s.ListenAndServe()http.ListenAndServe()(package-level function): Internally creates anhttp.Serverthat usesDefaultServeMuxas the handler.s.ListenAndServe()(method): When setting uphttp.Servermanually, this method uses the handler you specifically assigned to theHandlerfield.
http.ServeMux#
- Request Router: If you fix
http.Server.Handlerto a singlehttp.Handler, it can only process one type of request.http.ServeMuxis used to dispatch (route) requests to different handlers based on the URL path. - Created via
http.NewServeMux(). - Implements the
http.Handlerinterface, so it can be assigned to theHandlerfield inhttp.Server.
Methods#
func (mux *ServeMux) Handle(pattern string, handler Handler)func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
Warning: Avoid using package-level functions like
http.Handle,http.HandleFunc,http.ListenAndServe, andhttp.ListenAndServeTLSoutside of trivial test programs.
- They work with
http.DefaultServeMux, a package-level instance of*http.ServeMux.- Since the
http.Serverinstance is created internally withinhttp.ListenAndServe, you cannot configure critical server properties like timeouts.
Middleware#
- Pattern: A function that takes an
http.Handlerand returns anhttp.Handler. The returned handler is usually a closure that performs some logic before or after calling the original handler.
func Middleware(handler http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
// wrap the context with stuff
req = req.WithContext(ctx)
handler.ServeHTTP(rw, req)
})
}Usage with ServeMux#
mux := http.NewServeMux()
mux.Handle("/hello", Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello!\n"))
})))
s := http.Server{
Addr: ":8080",
Handler: mux,
}
s.ListenAndServe()