summaryrefslogblamecommitdiff
path: root/cmd/serve/serve.go
blob: 8591084d29700813c4ec0b7a850f27fa8653a31b (plain) (tree)


































































                                                                                                                          
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)
	},
}