package api import ( "fmt" "log" "net/http" "strconv" "srs.epita.fr/fic-server/libfic" "github.com/gin-gonic/gin" ) func declareThemesRoutes(router *gin.RouterGroup) { router.GET("/themes", listThemes) router.GET("/themes.json", exportThemes) themesRoutes := router.Group("/themes/:thid") themesRoutes.Use(themeHandler) themesRoutes.GET("", showTheme) declareExercicesRoutes(themesRoutes) } func themeHandler(c *gin.Context) { var theme *fic.Theme if thid, err := strconv.ParseInt(string(c.Param("thid")), 10, 64); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": "Bad theme identifier."}) return } else if theme, err = fic.GetTheme(thid); err != nil { c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Theme not found."}) return } c.Set("theme", theme) c.Next() } func listThemes(c *gin.Context) { themes, err := fic.GetThemes() if err != nil { log.Println("Unable to GetThemes: ", err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to list themes: %s", err.Error())}) return } c.JSON(http.StatusOK, themes) } func exportThemes(c *gin.Context) { themes, err := fic.ExportThemes() if err != nil { log.Println("Unable to ExportThemes: ", err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to export themes: %s", err.Error())}) return } c.JSON(http.StatusOK, themes) } func showTheme(c *gin.Context) { c.JSON(http.StatusOK, c.MustGet("theme")) }