-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
76 lines (61 loc) · 1.61 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
package main
import (
"errors"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
var (
ListenAddr = "localhost:8080"
RedisAddr = "localhost:6379"
Password = "" // you can omit it if you didn't set the pwd
)
func initRouter(database *Database) *gin.Engine {
r := gin.Default()
// add user
r.POST("/points", func(ctx *gin.Context) {
var userJson User
if err := ctx.ShouldBindJSON(&userJson); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err := database.SaveUser(&userJson)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"user": userJson})
})
// query user
r.GET("/points/:username", func(ctx *gin.Context) {
username := ctx.Param("username")
user, err := database.GetUser(username)
if err != nil {
if errors.Is(err, ErrNil) {
ctx.JSON(http.StatusNotFound, gin.H{"error": "No record found for " + username})
return
}
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"user": user})
})
// get leaderboard
r.GET("/leaderboard", func(ctx *gin.Context) {
leaderboard, err := database.GetLeaderboard()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"leaderboard": leaderboard})
})
return r
}
func main() {
database, err := NewDatabase(RedisAddr, Password)
if err != nil {
log.Fatalf("Failed to connect to redis: %v", err)
}
router := initRouter(database)
log.Fatal(router.Run(ListenAddr))
}