Standard library / net/http

http.Server.Shutdown()

Stops accepting connections and waits for ordinary active requests to finish until the supplied context expires. Does not manage hijacked connections. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func (srv *Server) Shutdown(ctx context.Context) error

Parameters & Attributes

NameTypeDescription
ctxcontext.ContextContext controlling cancellation.

Return Value

error

Nil after ordinary connections drain, or an error such as context expiration.

Working Example

Example Snippetgo
package main
import (  "bytes"  "context"  "errors"  "fmt"  "io"  "mime/multipart"  "net"  "net/http"  "net/http/httptest"  "strings"  "time")
func main() {  s, u, done := localServer()  defer s.Close()  c := &http.Client{Timeout: time.Second}  r := must(c.Get(u))  defer r.Body.Close()  check(r.Body.Close())  ctx, cancel := context.WithTimeout(context.Background(), time.Second)  defer cancel()  check(s.Shutdown(ctx))  fmt.Println(errors.Is(<-done, http.ErrServerClosed))}func rec(h http.Handler, method, path string) *httptest.ResponseRecorder {  w := httptest.NewRecorder()  h.ServeHTTP(w, httptest.NewRequest(method, path, nil))  return w}func fixture() *httptest.Server {  return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }))}func localServer() (*http.Server, string, chan error) {  l := must(net.Listen("tcp4", "127.0.0.1:0"))  s := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }), ReadHeaderTimeout: time.Second}  done := make(chan error, 1)  go func() { done <- s.Serve(l) }()  return s, "http://" + l.Addr().String(), done}func form() *http.Request {  r := httptest.NewRequest("POST", "/?q=query", strings.NewReader("q=body&name=Go"))  r.Header.Set("Content-Type", "application/x-www-form-urlencoded")  return r}func multipartReq() *http.Request {  var b bytes.Buffer  w := multipart.NewWriter(&b)  f := must(w.CreateFormFile("upload", "demo.txt"))  _, e := io.WriteString(f, "hello")  check(e)  check(w.Close())  r := httptest.NewRequest("POST", "/", &b)  r.Header.Set("Content-Type", w.FormDataContentType())  return r}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference