package api import ( "github.com/gin-gonic/gin" db "main.go/database" "main.go/tools" . "main.go/type" ) //GetAllScore 获取所有的积分,按照积分降序排列 func GetAllScore(c *gin.Context){ var s ScoreResponse var scores []ScoreResponse Link() DB :=db.DBsnctf //rows,err := DB.Raw("SELECT s.id, s.username, s.score FROM score AS s, user AS u WHERE u.hidden = 0 AND s.username = u.username ORDER BY s.score DESC;").Scan(&s).Rows() rows,err := DB.Debug().Raw("SELECT s.id, s.username, s.score FROM score AS s, user AS u WHERE u.hidden = 0 AND s.username = u.username ORDER BY s.score DESC;").Rows() if err != nil { c.JSON(400, gin.H{"code": 400, "msg": "Get all score error!"}) return } // 循环读取数据 for rows.Next() { rows.Scan(&s.ID, &s.Username, &s.Score) scores = append(scores, s) } c.JSON(200, gin.H{"code": 200, "data": scores}) } //GetScoreByUserId 获取用户分数 func GetScoreByUserId(c *gin.Context) { var score int Link() DB := db.DBsnctf //获取用户id id := c.Params.ByName("id") if id == "" { c.JSON(400, gin.H{"code": 400, "msg": "Need id!"}) return } //检查id是否合法 if !tools.CheckID(id) { c.JSON(400, gin.H{"code": 400, "msg": "ID format error!"}) return } //查询用户信息 err := DB.Raw("SELECT s.score FROM score AS s, user AS u WHERE u.id = ? AND u.hidden = 0 AND u.username = s.username LIMIT 1;", id).Scan(&score).Error if err != nil { c.JSON(400, gin.H{"code": 400, "msg": "Get info error!"}) return } c.JSON(200, gin.H{"code": 200, "data": score}) } //GetSelfScoreAndRank 获取当前登录用户的分数和排名 func GetSelfScoreAndRank(c *gin.Context){ var scoreAndRank ScoreRankResponse DB := db.DBsnctf session, err := Store.Get(c.Request, "SNCTFSESSID") if err != nil { c.JSON(200, gin.H{"code": 400, "msg": "Get SNCTFSESSID error"}) return } user, ok := session.Values["user"].(User) if !ok { c.JSON(200, gin.H{"code": 400, "msg": "No session"}) return } err = DB.Raw("SELECT score, (SELECT count(DISTINCT score) FROM score WHERE score>=s.score) AS rank FROM score AS s,user AS u WHERE u.id = ? AND u.username = s.username ORDER BY score DESC LIMIT 1;",user.ID).Scan(&scoreAndRank).Error if err != nil { c.JSON(200, gin.H{"code": 400, "msg": "Get info error!"}) return } c.JSON(200, gin.H{"code": 200, "data": scoreAndRank}) }