9 "git.immae.eu/Cryptoportfolio/Front.git/api"
10 "git.immae.eu/Cryptoportfolio/Front.git/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 {
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)
64 api.SetMailConfig(C.Mail)
66 db.Init(C.Db, C.Redis)
69 gin.DisableConsoleColor()
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{
156 for _, route := range availableRoutes {
157 appGroup.StaticFile(route, path.Join(C.App.PublicDir, "/index.html"))
160 engine.Run(strings.Join([]string{C.Address, C.Port}, ":"))