-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
100 lines (79 loc) · 1.79 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
package main
import (
"context"
// "os/user"
"fmt"
"log"
"net/http"
"strconv"
"sort"
firebase "firebase.google.com/go"
"github.com/gin-gonic/gin"
"google.golang.org/api/iterator"
"google.golang.org/appengine"
)
type User struct {
Name string `json:"name"`
Score int `json:"score"`
}
type Ranking struct {
Rank1 User `json:"rank1"`
Rank2 User `json:"rank2"`
Rank3 User `json:"rank3"`
Rank4 User `json:"rank4"`
Rank5 User `json:"rank5"`
}
func main() {
router := gin.Default()
ctx := context.Background()
conf := &firebase.Config{ProjectID: "tng-pjam2019"}
app, err := firebase.NewApp(ctx, conf)
if err != nil {
log.Fatalln(err)
}
client, err := app.Firestore(ctx)
if err != nil {
log.Fatalln(err)
}
defer client.Close()
router.GET("/getRanking/:number", func(c *gin.Context) {
iter := client.Collection("user").Documents(ctx)
var resultData []User
number := c.Params.ByName("number")
num, _ := strconv.Atoi(number)
for {
doc, err := iter.Next()
var tmp User
if err == iterator.Done {
break
}
if err != nil {
return
}
fmt.Println(doc.Data())
doc.DataTo(&tmp)
resultData = append(resultData, tmp)
}
sort.Slice(resultData, func(i, j int) bool {
return resultData[i].Score > resultData[j].Score
})
var res string
tmpNum := strconv.Itoa(resultData[num-1].Score)
res = number + "位" + " " + resultData[num-1].Name + " " + tmpNum
c.String(200, res)
})
router.POST("/postResult", func(c *gin.Context) {
var user User
c.BindJSON(&user)
_, _, err := client.Collection("user").Add(ctx, map[string]interface{}{
"name": user.Name,
"score": user.Score,
})
if err != nil {
log.Printf("An error has occurred: %s", err)
}
c.String(http.StatusOK, "Hello!")
})
http.Handle("/", router)
appengine.Main()
}