-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
116 lines (86 loc) · 2.21 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"encoding/json"
"github.com/valyala/fasthttp"
"log"
)
type RegisterEventRequest struct {
Event string
}
type StatusResponce struct {
Status string
}
type CardinalityRequest struct {
From uint32
To uint32
}
type CardinalityResponce struct {
Value uint64
}
func MakeHttpServer(addr string, eventRegistrator IEventRegistrator) *fasthttp.Server {
handler := func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/event":
var event RegisterEventRequest
status := "fail"
code := fasthttp.StatusInternalServerError
var err error
err = json.Unmarshal(ctx.PostBody(), &event)
if err != nil {
log.Println(err)
code = fasthttp.StatusBadRequest
} else {
err = eventRegistrator.AddEvent(event.Event)
if err != nil {
log.Println(err)
} else {
status = "ok"
code = fasthttp.StatusOK
}
}
writeJson(ctx, code, StatusResponce{Status: status})
case "/info":
var infoRequest CardinalityRequest
var info CardinalityResponce
err := json.Unmarshal(ctx.PostBody(), &infoRequest)
if err != nil {
log.Println(err)
writeJson(ctx, fasthttp.StatusBadRequest, StatusResponce{Status: "fail"})
return
}
log.Println("infoRequest", infoRequest)
info.Value = 0
count, err := eventRegistrator.GetCardinality(infoRequest.From, infoRequest.To)
if err != nil {
log.Println(err)
writeJson(ctx, fasthttp.StatusInternalServerError, StatusResponce{Status: "fail"})
return
}
writeJson(ctx, fasthttp.StatusInternalServerError, CardinalityResponce{Value: count})
default:
ctx.Error("Unsupported path", fasthttp.StatusNotFound)
}
}
s := &fasthttp.Server{
Handler: handler,
}
go func() {
err := s.ListenAndServe(addr)
if err != nil {
log.Println(err)
return
}
}()
return s
}
var (
strContentType = []byte("Content-Type")
strApplicationJSON = []byte("application/json")
)
func writeJson(ctx *fasthttp.RequestCtx, code int, obj interface{}) {
ctx.Response.Header.SetCanonical(strContentType, strApplicationJSON)
ctx.Response.SetStatusCode(code)
if err := json.NewEncoder(ctx).Encode(obj); err != nil {
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
}
}