-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
278 lines (233 loc) · 5.44 KB
/
main.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package main
import (
"embed"
"log"
"strings"
// "encoding/json"
"fmt"
"github.com/gofiber/fiber/v2"
"gorm.io/gorm"
"github.com/glebarez/sqlite"
"github.com/go-playground/validator/v10"
"github.com/gofiber/template/html/v2"
)
type (
Difficulty int
Score struct {
gorm.Model
Name string `json:"name" validate:"required,min=1,max=20"`
Score int `json:"score"`
Time int `json:"time"`
Difficulty Difficulty `json:"difficulty" validate:"required"`
}
ErrorResponse struct {
Error bool
FailedField string
Tag string
Value interface{}
}
XValidator struct {
validator *validator.Validate
}
GlobalErrorHandlerResp struct {
Success bool `json:"success"`
Message string `json:"message"`
}
)
//go:embed web/*
var webfs embed.FS
func main() {
engine := html.New("./views", ".html")
db, err := Connect("./fiber.sql")
if err != nil {
panic(err)
}
app := fiber.New(fiber.Config{
Views: engine,
ErrorHandler: func(c *fiber.Ctx, err error) error {
return c.Status(fiber.StatusBadRequest).JSON(GlobalErrorHandlerResp{
Success: false,
Message: err.Error(),
})
},
})
app.Static("/", "./web")
api := app.Group("/api")
v1 := api.Group("/v1", func(c *fiber.Ctx) error { // middleware for /api/v1
c.Set("Version", "v1")
return c.Next()
})
v1.Get("/new", FiberHandler(ScoreBoardForm, db))
v1.Get("/scoreboard", FiberHandler(ShowScoreBoard, db))
v1.Get("/form", FiberHandler(Form, db))
// app.Listen(":3000")
panic(app.Listen(":3000"))
}
// let rec quicksort = function
// | [] -> []
// | x::xs -> let smaller, larger = List.partition (fun y -> y < x) xs
// in quicksort smaller @ (x::quicksort larger)
func cmp(s, s2 Score) bool {
return s.Score > s2.Score || (s.Score == s2.Score) && s.Time < s2.Time
}
func quicksort(i []Score) []Score {
switch len(i) {
case 0, 1:
return i
default:
pivot := i[0]
var left, right []Score
for _, score := range i[1:] {
if cmp(score, pivot) {
left = append(left, score)
} else {
right = append(right, score)
}
}
left = quicksort(left)
right = quicksort(right)
sorted := append(append(left, pivot), right...)
return sorted
}
}
// TODO remove duplicates
func difficulty_of_int(i int) (Difficulty, error) {
switch i {
case 1:
return 1, nil
case 2:
return 2, nil
case 3:
return 3, nil
default:
return 0, fmt.Errorf("error invalid difficulty")
}
}
// Params:
// name: string min=1 max=20 time=1000
func ScoreBoardForm(c *fiber.Ctx, db *gorm.DB) error {
log.Printf("Leaderboard req: %v\n", c.String())
difficulty, err := difficulty_of_int(c.QueryInt("difficulty"))
if err != nil {
return err
}
userScore := Score{
Name: c.Query("name"),
Score: c.QueryInt("score"),
Time: c.QueryInt("time"),
Difficulty: difficulty,
}
myValidator := &XValidator{
validator: validate,
}
// Validation
if errs := myValidator.Validate(userScore); len(errs) > 0 && errs[0].Error {
errMsgs := make([]string, 0)
for _, err := range errs {
errMsgs = append(errMsgs, fmt.Sprintf(
"[%s]: '%v' | Needs to implement '%s'",
err.FailedField,
err.Value,
err.Tag,
))
}
return &fiber.Error{
Code: fiber.ErrBadRequest.Code,
Message: strings.Join(errMsgs, " and "),
}
}
db.Create(&userScore)
fmt.Printf("%v", userScore)
return c.SendString("aaaa")
}
func filter(i []Score, f func(Score) bool) []Score {
switch len(i) {
case 0:
return []Score{}
case 1:
if f(i[0]) {
return i
} else {
return []Score{}
}
default:
h := i[0]
t := i[1:]
if f(h) {
return append([]Score{h}, filter(t, f)...)
} else {
return filter(t, f)
}
}
}
func Form(c *fiber.Ctx, db *gorm.DB) error {
return c.Render("form", fiber.Map{})
}
func max(a, b int) int {
if a < b {
return b
}
return a
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func ShowScoreBoard(c *fiber.Ctx, db *gorm.DB) error {
var people []Score
db.Find(&people)
ff := func(p []Score) []Score {
max := min(len(p), 10) // max index
return quicksort(p)[0:max]
}
filt := func(i int) func(Score) bool {
return func(s Score) bool {
n, err := difficulty_of_int(i)
if err != nil {
panic("filter invalid difficulty")
}
return s.Difficulty == n
}
}
people1 := filter(people, filt(1))
people2 := filter(people, filt(2))
people3 := filter(people, filt(3))
log.Println(ff(people1))
return c.Render("scoreboard", fiber.Map{
"People1": ff(people1),
"People2": ff(people2),
"People3": ff(people3),
})
}
func FiberHandler(fn func(*fiber.Ctx, *gorm.DB) error, db *gorm.DB) fiber.Handler {
return func(c *fiber.Ctx) error {
return fn(c, db)
}
}
func Connect(path string) (*gorm.DB, error) {
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(Score{})
return db, nil
}
var validate = validator.New()
func (v XValidator) Validate(data interface{}) []ErrorResponse {
validationErrors := []ErrorResponse{}
errs := validate.Struct(data)
if errs != nil {
for _, err := range errs.(validator.ValidationErrors) {
// In this case data object is actually holding the User struct
var elem ErrorResponse
elem.FailedField = err.Field() // Export struct field name
elem.Tag = err.Tag() // Export struct tag
elem.Value = err.Value() // Export field value
elem.Error = true
validationErrors = append(validationErrors, elem)
}
}
return validationErrors
}