9 "immae.eu/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front/api"
10 "immae.eu/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front/db"
12 "github.com/gin-contrib/cors"
13 "github.com/gin-gonic/gin"
14 "github.com/jloup/utils"
17 var log = utils.StandardL().WithField("module", "api")
19 type AppConfig struct {
20 PublicDir string `toml:"public_dir"`
23 type ApiConfig struct {
24 Domain string `toml:"domain"`
25 JwtSecret string `toml:"jwt_secret"`
33 utils.LogConfiguration
39 func (c *Config) SetToDefaults() {
45 PublicDir: "./public",
52 c.LogConfiguration.SetToDefaults()
58 utils.MustParseStdConfigFile(&C)
60 err := utils.ConfigureStdLogger(C.LogConfiguration)
65 api.SetJwtSecretKey(C.Api.JwtSecret)
69 if C.Mode == "production" {
70 gin.SetMode(gin.ReleaseMode)
74 log.Infof("LISTEN: %s", strings.Join([]string{C.Address, C.Port}, ":"))
75 log.Infof("PUBLIC_DIR: %s", C.App.PublicDir)
78 func SetApiRoute(router *gin.RouterGroup, route api.Route) {
81 router.GET(route.Path, route.Handlers...)
83 router.POST(route.Path, route.Handlers...)
85 router.OPTIONS(route.Path, route.Handlers...)
87 panic(fmt.Errorf("%s method not handled", route.Method))
91 func SetGroup(router *gin.RouterGroup, group api.Group) {
92 var r *gin.RouterGroup
96 r = router.Group(group.Root)
99 if group.Middlewares != nil {
100 for _, middleware := range group.Middlewares {
101 r.Use(api.M(middleware))
105 for _, route := range group.Routes {
106 SetApiRoute(r, route)
113 apiGroup := engine.Group("/api")
116 engine.Use(gin.Recovery())
118 if C.Mode == "production" {
119 engine.Use(api.Logger())
120 apiGroup.Use(api.Logger())
122 engine.Use(gin.Logger())
123 apiGroup.Use(gin.Logger())
126 apiGroup.Use(cors.New(cors.Config{
127 AllowOrigins: []string{fmt.Sprintf("https://%s", C.Api.Domain)},
128 AllowMethods: []string{"POST", "GET", "OPTIONS"},
129 AllowHeaders: []string{"Authorization"},
130 ExposeHeaders: []string{"Authorization"},
131 AllowCredentials: true,
132 MaxAge: 12 * time.Hour,
135 for _, group := range api.Groups {
136 SetGroup(apiGroup, group)
139 appGroup.Static("/public", C.App.PublicDir)
140 availableRoutes := []string{
150 for _, route := range availableRoutes {
151 appGroup.StaticFile(route, path.Join(C.App.PublicDir, "/index.html"))
154 engine.Run(strings.Join([]string{C.Address, C.Port}, ":"))