/
routes.go
59 lines (44 loc) · 1.14 KB
/
routes.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
package main
import (
"fmt"
"log"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
)
type response struct {
Message string `json:"message"`
}
const appContext = "/logour/v1"
var (
strContentType = []byte("Content-Type")
strApplicationJSON = []byte("application/json")
)
func mountRoutes(r *fasthttprouter.Router, db *DB) {
r.GET(appContext+"/health", func(c *fasthttp.RequestCtx) {
_, err := fmt.Fprintf(c, "OK")
if err != nil {
log.Println("Unable to handle http request")
}
})
r.POST(appContext+"/event", func(ctx *fasthttp.RequestCtx) {
if len(ctx.PostBody()) == 0 {
ctx.Response.SetStatusCode(400)
return
}
reqInfo := extractReqInfo(ctx)
go createEvent(ctx.PostBody(), reqInfo, db)
end(ctx, 200)
})
}
func extractReqInfo(ctx *fasthttp.RequestCtx) *RequestInfo {
return &RequestInfo{
IP: ctx.RemoteAddr().String(),
UserAgent: string(ctx.UserAgent()),
}
}
func end(ctx *fasthttp.RequestCtx, code int) {
ctx.Response.Header.SetCanonical(strContentType, strApplicationJSON)
ctx.Response.SetStatusCode(code)
ctx.SetBody([]byte("{\"message\":\"OK\"}"))
ctx.SetConnectionClose()
}