/
server.go
75 lines (68 loc) · 1.97 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
75
package server
import (
"encoding/json"
"fmt"
"log"
"strconv"
"time"
"github.com/buaazp/fasthttprouter"
"github.com/rafax/tokenz/token"
"github.com/valyala/fasthttp"
)
type Server struct {
bindTo string
router *fasthttprouter.Router
}
func NewServer(bindTo string, handlers map[string]token.Handler) *Server {
router := fasthttprouter.New()
router.GET("/statusz", func(ctx *fasthttp.RequestCtx) {
fmt.Fprint(ctx, "OK")
})
for k, h := range handlers {
router.POST(fmt.Sprintf("/%v/:userId/:valid_seconds/:level/:platform", k), encode(h))
router.GET(fmt.Sprintf("/%v/:token", k), decode(h))
}
return &Server{bindTo: bindTo, router: router}
}
func (s *Server) Start() {
fmt.Printf("Listening on %s\n", s.bindTo)
log.Fatal(fasthttp.ListenAndServe(s.bindTo, s.router.Handler))
}
func decode(h token.Handler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
t := ctx.UserValue("token").(string)
sd, err := h.Decrypt(token.StringToken{Token: t})
if err != nil {
ctx.Error(fmt.Sprintf("Error when decrypting token: %s", err), 500)
return
}
j, err := json.Marshal(sd)
if err != nil {
ctx.Error(fmt.Sprintf("Error when marshalling response: %s", err), 500)
return
}
fmt.Fprint(ctx, string(j))
}
}
func encode(h token.Handler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
validForSeconds, err := strconv.Atoi(ctx.UserValue("valid_seconds").(string))
if err != nil {
ctx.Error(fmt.Sprintf("Error when parsing valid_seconds: %s", err), 500)
return
}
sd := token.SubscriptionData{
ExpiresAt: time.Now().Add(time.Second * time.Duration(validForSeconds)),
UserId: ctx.UserValue("userId").(string),
Platform: ctx.UserValue("platform").(string),
Level: ctx.UserValue("level").(string),
}
log.Println(sd)
t, err := h.Encrypt(sd)
if err != nil {
ctx.Error(fmt.Sprintf("Error when encrypting to token: %s", err), 500)
return
}
fmt.Fprintf(ctx, "{\"token\": \"%s\"}", t.String())
}
}