- commit
- d5f6909fa5d5d913b417dc8ea92652b552e5f5e0
- parent
- 420c90d5905eafa8b13303d6b01b82b7b4819c9d
- Author
- Tobias Bengfort <tobias.bengfort@posteo.de>
- Date
- 2024-02-11 17:37
graceful shutdown - call Shutdown to close connections before exit - exit with status 0 on shutdown - call Shutdown in the main thread because it blocks while ListenAndServe exits immediately - Shutdown waits for requests to complete. We pass the signal context to the server so it derives the request contexts from that. The long-running GET request handler already stop on context cancellation. - unregister signals before shutdown so that a second Ctrl-C will hard-exit https://dev.to/mokiat/proper-http-shutdown-in-go-3fji https://erictse.dev/posts/graceful-go-http-server/
Diffstat
| M | via.go | 24 | ++++++++++++++++++++++-- |
1 files changed, 22 insertions, 2 deletions
diff --git a/via.go b/via.go
@@ -1,18 +1,22 @@ 1 1 package main 2 2 3 3 import ( -1 4 "context" 4 5 "encoding/base64" 5 6 "encoding/json" 6 7 "flag" 7 8 "fmt" 8 9 "io/ioutil" 9 10 "log" -1 11 "net" 10 12 "net/http" 11 13 "os" -1 14 "os/signal" 12 15 "path" 13 16 "strconv" 14 17 "strings" 15 18 "sync" -1 19 "syscall" 16 20 "time" 17 21 ) 18 22 @@ -371,6 +375,22 @@ func main() { 371 375 http.HandleFunc("/msg/", handler) 372 376 http.HandleFunc("/hmsg/", handler) 373 377374 -1 log.Printf("Serving on http://%s", addr)375 -1 log.Fatal(http.ListenAndServe(addr, nil))-1 378 ctx, unregisterSignals := signal.NotifyContext( -1 379 context.Background(), os.Interrupt, syscall.SIGTERM, -1 380 ) -1 381 ctxFactory := func(l net.Listener) context.Context { return ctx } -1 382 server := &http.Server{Addr: addr, BaseContext: ctxFactory} -1 383 -1 384 go func() { -1 385 log.Printf("Serving on http://%s", addr) -1 386 err := server.ListenAndServe() -1 387 if err != http.ErrServerClosed { -1 388 log.Fatal(err) -1 389 } -1 390 }() -1 391 -1 392 <-ctx.Done() -1 393 unregisterSignals() -1 394 log.Println("Shutting down server…") -1 395 server.Shutdown(context.Background()) 376 396 }