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 {
25 Domain string `toml:"domain"`
34 utils.LogConfiguration
40 func (c *Config) SetToDefaults() {
46 PublicDir: "./public",
50 c.LogConfiguration.SetToDefaults()
56 utils.MustParseStdConfigFile(&C)
58 err := utils.ConfigureStdLogger(C.LogConfiguration)
63 api.SetConfig(C.Api.Config)
65 db.Init(C.Db, C.Redis)
67 if C.Mode == "production" {
68 gin.SetMode(gin.ReleaseMode)
72 log.Infof("LISTEN: %s", strings.Join([]string{C.Address, C.Port}, ":"))
73 log.Infof("PUBLIC_DIR: %s", C.App.PublicDir)
76 func SetApiRoute(router *gin.RouterGroup, route api.Route) {
79 router.GET(route.Path, route.Handlers...)
81 router.POST(route.Path, route.Handlers...)
83 router.OPTIONS(route.Path, route.Handlers...)
85 panic(fmt.Errorf("%s method not handled", route.Method))
89 func SetGroup(router *gin.RouterGroup, group api.Group) {
90 var r *gin.RouterGroup
94 r = router.Group(group.Root)
97 if group.Middlewares != nil {
98 for _, middleware := range group.Middlewares {
99 r.Use(api.M(middleware))
103 for _, route := range group.Routes {
104 SetApiRoute(r, route)
111 apiGroup := engine.Group("/api")
114 engine.Use(gin.Recovery())
116 if C.Mode == "production" {
117 engine.Use(api.Logger())
118 apiGroup.Use(api.Logger())
120 engine.Use(gin.Logger())
121 apiGroup.Use(gin.Logger())
124 apiGroup.Use(cors.New(cors.Config{
125 AllowOrigins: []string{fmt.Sprintf("https://%s", C.Api.Domain)},
126 AllowMethods: []string{"POST", "GET", "OPTIONS"},
127 AllowHeaders: []string{"Authorization"},
128 ExposeHeaders: []string{"Authorization"},
129 AllowCredentials: true,
130 MaxAge: 12 * time.Hour,
133 for _, group := range api.Groups {
134 SetGroup(apiGroup, group)
137 appGroup.Static("/public", C.App.PublicDir)
138 availableRoutes := []string{
151 for _, route := range availableRoutes {
152 appGroup.StaticFile(route, path.Join(C.App.PublicDir, "/index.html"))
155 engine.Run(strings.Join([]string{C.Address, C.Port}, ":"))