qa: Use gin
This commit is contained in:
parent
9fd5564410
commit
abdf146fea
13 changed files with 596 additions and 378 deletions
|
@ -1,36 +1,58 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"srs.epita.fr/fic-server/libfic"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func init() {
|
||||
router.GET("/api/exercices/", apiHandler(listExercices))
|
||||
func declareExercicesRoutes(router *gin.RouterGroup) {
|
||||
router.GET("/exercices", listExercices)
|
||||
|
||||
router.GET("/api/exercices/:eid", apiHandler(exerciceHandler(showExercice)))
|
||||
exercicesRoutes := router.Group("/exercices/:eid")
|
||||
exercicesRoutes.Use(exerciceHandler)
|
||||
exercicesRoutes.GET("", showExercice)
|
||||
}
|
||||
|
||||
func exerciceHandler(f func(QAUser, *fic.Exercice, []byte) (interface{}, error)) func(QAUser, httprouter.Params, []byte) (interface{}, error) {
|
||||
return func(u QAUser, ps httprouter.Params, body []byte) (interface{}, error) {
|
||||
if eid, err := strconv.ParseInt(string(ps.ByName("eid")), 10, 64); err != nil {
|
||||
return nil, err
|
||||
} else if exercice, err := fic.GetExercice(eid); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return f(u, exercice, body)
|
||||
func exerciceHandler(c *gin.Context) {
|
||||
var exercice *fic.Exercice
|
||||
if eid, err := strconv.ParseInt(string(c.Param("eid")), 10, 64); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Bad exercice identifier."})
|
||||
return
|
||||
} else if exercice, err = fic.GetExercice(eid); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Exercice not found."})
|
||||
return
|
||||
}
|
||||
|
||||
if th, ok := c.Get("theme"); ok {
|
||||
if exercice.IdTheme != th.(*fic.Theme).Id {
|
||||
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Exercice not found."})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.Set("exercice", exercice)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
func listExercices(_ QAUser, _ httprouter.Params, body []byte) (interface{}, error) {
|
||||
func listExercices(c *gin.Context) {
|
||||
// List all exercices
|
||||
return fic.GetExercices()
|
||||
exercices, err := fic.GetExercices()
|
||||
if err != nil {
|
||||
log.Println("Unable to GetExercices: ", err.Error())
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to list exercices: %s", err.Error())})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, exercices)
|
||||
}
|
||||
|
||||
func showExercice(_ QAUser, exercice *fic.Exercice, body []byte) (interface{}, error) {
|
||||
return exercice, nil
|
||||
func showExercice(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, c.MustGet("exercice"))
|
||||
}
|
||||
|
|
Reference in a new issue