Created
April 2, 2022 11:38
-
-
Save pallabpain/57b8dfbc102b4a79627972c939e4465c to your computer and use it in GitHub Desktop.
Starting a go http server with cancellable context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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