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"`
34 utils.LogConfiguration
40 func (c *Config) SetToDefaults() {
46 PublicDir: "./public",
53 c.LogConfiguration.SetToDefaults()
59 utils.MustParseStdConfigFile(&C)
61 err := utils.ConfigureStdLogger(C.LogConfiguration)
66 api.SetJwtSecretKey(C.Api.JwtSecret)
68 db.Init(C.Db, C.Redis)
70 if C.Mode == "production" {
71 gin.SetMode(gin.ReleaseMode)
75 log.Infof("LISTEN: %s", strings.Join([]string{C.Address, C.Port}, ":"))
76 log.Infof("PUBLIC_DIR: %s", C.App.PublicDir)
79 func SetApiRoute(router *gin.RouterGroup, route api.Route) {
82 router.GET(route.Path, route.Handlers...)
84 router.POST(route.Path, route.Handlers...)
86 router.OPTIONS(route.Path, route.Handlers...)
88 panic(fmt.Errorf("%s method not handled", route.Method))
92 func SetGroup(router *gin.RouterGroup, group api.Group) {
93 var r *gin.RouterGroup
97 r = router.Group(group.Root)
100 if group.Middlewares != nil {
101 for _, middleware := range group.Middlewares {
102 r.Use(api.M(middleware))
106 for _, route := range group.Routes {
107 SetApiRoute(r, route)
114 apiGroup := engine.Group("/api")
117 engine.Use(gin.Recovery())
119 if C.Mode == "production" {
120 engine.Use(api.Logger())
121 apiGroup.Use(api.Logger())
123 engine.Use(gin.Logger())
124 apiGroup.Use(gin.Logger())
127 apiGroup.Use(cors.New(cors.Config{
128 AllowOrigins: []string{fmt.Sprintf("https://%s", C.Api.Domain)},
129 AllowMethods: []string{"POST", "GET", "OPTIONS"},
130 AllowHeaders: []string{"Authorization"},
131 ExposeHeaders: []string{"Authorization"},
132 AllowCredentials: true,
133 MaxAge: 12 * time.Hour,
136 for _, group := range api.Groups {
137 SetGroup(apiGroup, group)
140 appGroup.Static("/public", C.App.PublicDir)
141 availableRoutes := []string{
152 for _, route := range availableRoutes {
153 appGroup.StaticFile(route, path.Join(C.App.PublicDir, "/index.html"))
156 engine.Run(strings.Join([]string{C.Address, C.Port}, ":"))