forked from imrenagicom/logging-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
67 lines (56 loc) · 1.41 KB
/
main.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
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
signal.Notify(ch, syscall.SIGTERM)
go func() {
oscall := <-ch
log.Warn().Msgf("system call:%+v", oscall)
cancel()
}()
r := mux.NewRouter()
r.HandleFunc("/", handler)
// start: set up any of your logger configuration here if necessary
// end: set up any of your logger configuration here
server := &http.Server{
Addr: ":8080",
Handler: r,
}
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal().Err(err).Msg("failed to listen and serve http server")
}
}()
<-ctx.Done()
if err := server.Shutdown(context.Background()); err != nil {
log.Error().Err(err).Msg("failed to shutdown http server gracefully")
}
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
name := r.URL.Query().Get("name")
res, err := greeting(ctx, name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte(res))
}
func greeting(ctx context.Context, name string) (string, error) {
if len(name) < 5 {
return fmt.Sprintf("Hello %s! Your name is to short\n", name), nil
}
return fmt.Sprintf("Hi %s", name), nil
}