-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
69 lines (51 loc) · 1.56 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
package daemon
import (
"pkg.re/essentialkaos/ek.v10/log"
"github.com/valyala/fasthttp"
)
// ////////////////////////////////////////////////////////////////////////////////// //
// startHTTPServer start HTTP server
func startHTTPServer(ip, port string) error {
addr := ip + ":" + port
log.Info("HTTP server is started on %s", addr)
server := fasthttp.Server{
Handler: fastHTTPHandler,
Name: APP + "/" + VER,
}
return server.ListenAndServe(addr)
}
// fastHTTPHandler handler for fast http requests
func fastHTTPHandler(ctx *fasthttp.RequestCtx) {
defer requestRecover(ctx)
path := string(ctx.Path())
if path != "/" {
ctx.SetStatusCode(404)
return
}
statusHandler(ctx)
}
// requestRecover recover panic in request
func requestRecover(ctx *fasthttp.RequestCtx) {
r := recover()
if r != nil {
log.Error("Recovered internal error in HTTP request handler: %v", r)
ctx.SetStatusCode(501)
}
}
// ////////////////////////////////////////////////////////////////////////////////// //
// statusHandler is status request handler
func statusHandler(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set("Content-Type", "application/json")
ctx.Response.Header.Set("Cache-Control", "no-cache, no-store, must-revalidate")
ctx.Response.Header.Set("Pragma", "no-cache")
ctx.Response.Header.Set("Expires", "0")
body, err := datastore.MarshalJSON()
if err != nil {
log.Warn("Internal Server Error while processing user request: %s", err.Error())
ctx.SetStatusCode(500)
return
}
log.Info("Respond with status 200")
ctx.Write(body)
ctx.SetStatusCode(200)
}