forked from RobinUS2/presto-bloomfilter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
74 lines (60 loc) · 1.35 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
70
71
72
73
74
package main
import (
"fmt"
"log"
"github.com/qiangxue/fasthttp-routing"
"github.com/valyala/fasthttp"
)
type Server struct {
requestHandler func(ctx *fasthttp.RequestCtx)
conf *Conf
router *routing.Router
backend IBackend
}
// Init
func (s *Server) init() {
// Backend
s.backend = newBackend(s.conf)
if s.backend == nil {
log.Fatal("Backend not initiated")
}
// Router
s.router = routing.New()
// Upsert operation that writes data
s.router.Put("/bloomfilter/<key>", func(c *routing.Context) error {
// Params
key := c.Param("key")
body := c.PostBody()
// Put
res, resErr := s.backend.Put([]byte(key), body)
// Log
log.Printf("PUT %v %d %v %v", key, len(body), res, resErr)
return nil
})
// Get
s.router.Get("/bloomfilter/<key>", func(c *routing.Context) error {
// Params
key := c.Param("key")
// Get
res, resErr := s.backend.Get([]byte(key))
// Output
fmt.Fprintf(c, "%s", res)
// Log
log.Printf("GET %v %d %v", key, len(res), resErr)
return nil
})
}
// Start
func (s *Server) Start() {
listenStr := fmt.Sprintf("%s:%d", s.conf.ListenHost, s.conf.ListenPort)
log.Printf("Starting server at %s", listenStr)
panic(fasthttp.ListenAndServe(listenStr, s.router.HandleRequest))
}
// Constructor
func newServer(conf *Conf) *Server {
s := &Server{
conf: conf,
}
s.init()
return s
}