-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
100 lines (81 loc) · 2.73 KB
/
handler.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
package handler
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/kainobor/slots/config"
"github.com/kainobor/slots/src/logger"
"github.com/kainobor/slots/src/processor"
)
type Handler struct {
config *config.Config
proc *processor.Processor
secret []byte
}
type SpinResponse struct {
Total int64 `json:"total"`
Spins []*processor.SpinResult `json:"spins"`
JWT string `json:"jwt"`
}
const (
SpinTypeMain = "main"
SpinTypeFree = "free"
)
// New request handler with config and processor
func New(conf *config.Config, proc *processor.Processor) *Handler {
h := new(Handler)
h.config = conf
h.proc = proc
h.secret = []byte(conf.Handler.Secret)
return h
}
// Spins is main method for generates outcome and check it for wins
func (h *Handler) Spins(w http.ResponseWriter, r *http.Request) {
start := time.Now().UnixNano()
pld, err := newPayload(r, h.secret)
if err != nil {
t := time.Now().UnixNano()
logger.Err("error while getting payload", "time", t, "error", err)
http.Error(w, fmt.Sprintf("Internal error at %d", t), 500)
return
}
newBalance := pld.Chips - pld.Bet*int64(len(h.config.Processor.Lines))
if newBalance < 0 {
http.Error(w, fmt.Sprintf("You're too poor"), 500)
return
}
resp := new(SpinResponse)
freeSpins := 0
for freeSpins >= 0 {
freeSpins--
outcome := h.proc.GenerateOutcome()
spin, err := h.proc.CheckWins(outcome, pld.Bet)
if err != nil {
t := time.Now().UnixNano()
logger.Err("error while checking wins", "time", t, "error", err, "outcome", outcome)
http.Error(w, fmt.Sprintf("Internal error at %d", time.Now().UnixNano()), 500)
return
}
spin.Type = SpinTypeMain
if spin.IsFree {
spin.Type = SpinTypeFree
freeSpins = freeSpins + h.config.Handler.FreeRollsByOneAddiction
}
resp.Total = resp.Total + spin.Total
resp.Spins = append(resp.Spins, spin)
logger.Log("Result", "outcome", outcome)
}
pld.Chips = newBalance + resp.Total
token := jwt.NewWithClaims(jwt.SigningMethodHS512, pld)
resp.JWT, err = token.SignedString([]byte(h.config.Handler.Secret))
if err != nil {
t := time.Now().UnixNano()
logger.Err("error while creating token", "time", t, "error", err, "response", resp)
http.Error(w, fmt.Sprintf("Internal error at %d", time.Now().UnixNano()), 500)
return
}
json.NewEncoder(w).Encode(resp)
logger.Log("Time", "duration", float64(time.Now().UnixNano()-start)/1000000000)
}