diff options
Diffstat (limited to 'cmd/serve/serve.go')
-rw-r--r-- | cmd/serve/serve.go | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/cmd/serve/serve.go b/cmd/serve/serve.go new file mode 100644 index 0000000..8591084 --- /dev/null +++ b/cmd/serve/serve.go @@ -0,0 +1,67 @@ +package serve + +import ( + "context" + "os" + "time" + + "git.neonxp.ru/neonxp/guessr/pkg/api" + "git.neonxp.ru/neonxp/guessr/pkg/config" + "git.neonxp.ru/neonxp/guessr/pkg/db" + "git.neonxp.ru/neonxp/guessr/pkg/middleware" + "git.neonxp.ru/neonxp/guessr/pkg/service" + "github.com/gorilla/sessions" + echosession "github.com/labstack/echo-contrib/session" + "github.com/labstack/echo/v4" + echomiddleware "github.com/labstack/echo/v4/middleware" + "github.com/urfave/cli/v3" + "golang.org/x/time/rate" +) + +var Command = &cli.Command{ + Name: "serve", + Usage: "start api server", + Action: func(ctx context.Context, c *cli.Command) error { + cfg, err := config.New() + if err != nil { + return err + } + dbClient := db.New(cfg.DB) + placesService := service.New(dbClient) + + apiHandler := api.New(placesService) + + e := echo.New() + e.Debug = cfg.Debug + + e.Use( + echomiddleware.Recover(), + echomiddleware.Logger(), + echomiddleware.RemoveTrailingSlash(), + ) + + func(g *echo.Group) { + g.Use( + echosession.Middleware(sessions.NewCookieStore([]byte(cfg.Keys[0]), []byte(cfg.Keys[1]))), + middleware.PopulateState(), + echomiddleware.RateLimiter( + echomiddleware.NewRateLimiterMemoryStore( + rate.Every(time.Second), + ), + ), + ) + g.POST("/next", apiHandler.PostNext) + g.POST("/guess", apiHandler.PostGuess) + g.GET("/state", apiHandler.GetState) + g.POST("/state", apiHandler.PostState) + }(e.Group("/api")) + + // if cfg.Debug { + e.StaticFS("/", os.DirFS("./static")) + // } else { + // e.StaticFS("/", static.FS) + // } + + return e.Start(cfg.Listen) + }, +} |