Skip to content

Instantly share code, notes, and snippets.

@pallabpain
Created April 2, 2022 11:38
Show Gist options
  • Save pallabpain/57b8dfbc102b4a79627972c939e4465c to your computer and use it in GitHub Desktop.
Save pallabpain/57b8dfbc102b4a79627972c939e4465c to your computer and use it in GitHub Desktop.
Starting a go http server with cancellable context
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
)
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
defer cancel()
s := http.Server{
Addr: ":8000",
Handler: nil,
}
go func() {
log.Println("starting server...")
if err := s.ListenAndServe(); err != nil {
if errors.Is(err, http.ErrServerClosed) {
log.Println("stopping server")
return
}
log.Println("server stopped: ", err)
}
}()
<-ctx.Done()
if err := s.Shutdown(context.Background()); err != nil {
log.Println("stopping server: ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment