Standard library / net/http

http.Server.RegisterOnShutdown()

Registers a callback started during graceful shutdown. Shutdown does not wait for callbacks to finish. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func (srv *Server) RegisterOnShutdown(f func())

Parameters & Attributes

NameTypeDescription
ffunc()Callback that initiates protocol-specific graceful shutdown. Do not block awaiting completion.

Working Example

Example Snippetgo
package main
import (  "context"  "fmt"  "net/http"  "time")
func main() {  s := &http.Server{}  done := make(chan struct{})  s.RegisterOnShutdown(func() { close(done) })  check(s.Shutdown(context.Background()))  select {  case <-done:    fmt.Println(true)  case <-time.After(time.Second):    panic("callback timeout")  }}
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