-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
54 lines (45 loc) · 1.1 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func StartHTTP() {
port := fmt.Sprintf(":%d", args.httpPort)
log.Printf("Starting HTTP server on %s", port)
// Create a mux for routing incoming requests
myHandler := http.NewServeMux()
// All URLs will be handled by this function
myHandler.HandleFunc("/", handleRequest)
s := &http.Server{
Addr: port,
Handler: myHandler,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
log.Print("Server Started")
<-done
log.Print("Server Stopped")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
// extra handling here
cancel()
}()
if err := s.Shutdown(ctx); err != nil {
log.Fatalf("Server Shutdown Failed:%+v", err)
}
log.Print("Server Exited Properly")
}