-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
67 lines (54 loc) · 1.5 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"
"encoding/json"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"github.com/BrightLocal/test-url-checker-ms/checker"
"github.com/BrightLocal/test-url-checker-ms/protocol"
)
const listenOn = "10007"
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
ctx := context.Background()
signals := make(chan os.Signal)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
mux := http.NewServeMux()
mux.Handle("/"+protocol.MethodCheckURLs, http.HandlerFunc(CheckURLs))
server := &http.Server{
Addr: ":" + listenOn,
Handler: mux,
}
go func() {
<-signals
log.Printf("Graceful shutdown initiated...")
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
server.Shutdown(ctx)
}()
log.Printf("Listen on :%s", listenOn)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen error: %s\n", err)
}
}
func CheckURLs(rw http.ResponseWriter, r *http.Request) {
var req protocol.ProfileRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
rw.WriteHeader(http.StatusInternalServerError)
if err := json.NewEncoder(rw).Encode(protocol.ProfileResponse{Error: err.Error()}); err != nil {
log.Printf("failed to marshal error response: %s", err)
}
return
}
resp := &protocol.ProfileResponse{URLCodes: checker.Query(req.URLs)}
if err := json.NewEncoder(rw).Encode(resp); err != nil {
log.Printf("failed to marshal response: %s", err)
}
}