Skip to content

Commit a11cdbb

Browse files
committed
add graceful shutdown
1 parent 4bf7764 commit a11cdbb

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed

httpserver/bin/amd64/httpserver

-116 KB
Binary file not shown.

httpserver/main.go

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
package main
22

33
import (
4+
"context"
45
"flag"
56
"fmt"
67
"io"
78
"log"
89
"net/http"
10+
"os"
11+
"os/signal"
12+
"syscall"
13+
"time"
914

1015
_ "net/http/pprof"
1116

@@ -15,22 +20,33 @@ import (
1520
func main() {
1621
flag.Set("v", "4")
1722
glog.V(2).Info("Starting http server...")
18-
http.HandleFunc("/", rootHandler)
19-
c, python, java := true, false, "no!"
20-
fmt.Println(c, python, java)
21-
err := http.ListenAndServe(":80", nil)
22-
// mux := http.NewServeMux()
23-
// mux.HandleFunc("/", rootHandler)
24-
// mux.HandleFunc("/healthz", healthz)
25-
// mux.HandleFunc("/debug/pprof/", pprof.Index)
26-
// mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
27-
// mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
28-
// mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
29-
// err := http.ListenAndServe(":80", mux)
30-
if err != nil {
31-
log.Fatal(err)
23+
mux := http.NewServeMux()
24+
mux.HandleFunc("/", rootHandler)
25+
srv := http.Server{
26+
Addr: ":80",
27+
Handler: mux,
3228
}
29+
done := make(chan os.Signal, 1)
30+
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
3331

32+
go func() {
33+
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
34+
log.Fatalf("listen: %s\n", err)
35+
}
36+
}()
37+
log.Print("Server Started")
38+
<-done
39+
log.Print("Server Stopped")
40+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
41+
defer func() {
42+
// extra handling here
43+
cancel()
44+
}()
45+
46+
if err := srv.Shutdown(ctx); err != nil {
47+
log.Fatalf("Server Shutdown Failed:%+v", err)
48+
}
49+
log.Print("Server Exited Properly")
3450
}
3551

3652
func healthz(w http.ResponseWriter, r *http.Request) {

0 commit comments

Comments
 (0)