-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathserver.go
73 lines (62 loc) · 1.48 KB
/
server.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func handleUserAPI(w http.ResponseWriter, r *http.Request) {
log.Println("I started processing the request")
defer r.Body.Close()
data, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v\n", err)
http.Error(
w, "Error reading body",
http.StatusInternalServerError,
)
return
}
log.Println(string(data))
fmt.Fprintf(w, "Hello world!")
log.Println("I finished processing the request")
}
func shutDown(ctx context.Context, s *http.Server, waitForShutdownCompletion chan struct{}) {
sigch := make(chan os.Signal, 1)
signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigch
log.Printf("Got signal: %v . Server shutting down.", sig)
childCtx, cancel := context.WithTimeout(
ctx, 30*time.Second,
)
defer cancel()
if err := s.Shutdown(childCtx); err != nil {
log.Printf("Error during shutdown: %v", err)
}
waitForShutdownCompletion <- struct{}{}
}
func main() {
listenAddr := os.Getenv("LISTEN_ADDR")
if len(listenAddr) == 0 {
listenAddr = ":8080"
}
waitForShutdownCompletion := make(chan struct{})
mux := http.NewServeMux()
mux.HandleFunc("/api/users/", handleUserAPI)
s := http.Server{
Addr: listenAddr,
Handler: mux,
}
go shutDown(context.Background(), &s, waitForShutdownCompletion)
err := s.ListenAndServe()
log.Print(
"Waiting for shutdown to complete..",
)
<-waitForShutdownCompletion
log.Fatal(err)
}