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 utilizes http.DefaultClient, which has no timeout. It is recommended to create and use a custom http.Client with a timeout.

Server#

http.Handler and http.HandlerFunc#

  • http.Handler Interface
    type Handler interface {
        ServeHTTP(ResponseWriter, *Request)
    }
  • http.HandlerFunc Adapter
    type HandlerFunc func(ResponseWriter, *Request)
    • The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

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.ResponseWriter is an interface, adding new methods would break backward compatibility. http.ResponseController provides access to extended functionality for the underlying concrete type.
    • If the wrapped http.ResponseWriter does not support a specific method, it returns http.ErrNotSupported via type assertion.
  • func NewResponseController(rw ResponseWriter) *ResponseController: Creates a ResponseController from an http.ResponseWriter.
  • func (c *ResponseController) Flush() error
  • func (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, use WithContext.
  • func (r *Request) WithContext(ctx context.Context) *Request: Returns a shallow copy of r with its context changed to ctx.
  • func (r *Request) ParseForm() error: Parses the raw query from the URL and updates r.Form. For POST, PUT, and PATCH requests, it also reads the request body as a form and updates r.PostForm and r.Form.
  • func (r *Request) FormValue(key string) string: Returns the first value for the named component of the query. FormValue calls ParseForm if 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 an http.Server that uses DefaultServeMux as the handler.
  • s.ListenAndServe() (method): When setting up http.Server manually, this method uses the handler you specifically assigned to the Handler field.

http.ServeMux#

  • Request Router: If you fix http.Server.Handler to a single http.Handler, it can only process one type of request. http.ServeMux is used to dispatch (route) requests to different handlers based on the URL path.
  • Created via http.NewServeMux().
  • Implements the http.Handler interface, so it can be assigned to the Handler field in http.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, and http.ListenAndServeTLS outside of trivial test programs.

  • They work with http.DefaultServeMux, a package-level instance of *http.ServeMux.
  • Since the http.Server instance is created internally within http.ListenAndServe, you cannot configure critical server properties like timeouts.

Middleware#

  • Pattern: A function that takes an http.Handler and returns an http.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()