11package main
22
33import (
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 (
1520func 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
3652func healthz (w http.ResponseWriter , r * http.Request ) {
0 commit comments