add gracefully shut down server
This commit is contained in:
38
httpserver.go
Normal file
38
httpserver.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StartHTTPServer cct
|
||||
func StartHTTPServer(address string, handler http.HandlerFunc) {
|
||||
stop := make(chan os.Signal, 1)
|
||||
|
||||
signal.Notify(stop, os.Interrupt)
|
||||
|
||||
srv := &http.Server{Addr: address}
|
||||
|
||||
http.HandleFunc("/", handler)
|
||||
|
||||
go func() {
|
||||
log.Print("listening on http://" + address)
|
||||
|
||||
if err := srv.ListenAndServe(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}()
|
||||
|
||||
<-stop
|
||||
|
||||
log.Print("Shutting down...")
|
||||
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
|
||||
srv.Shutdown(ctx)
|
||||
|
||||
log.Print("Shut Down")
|
||||
}
|
||||
Reference in New Issue
Block a user