summaryrefslogtreecommitdiff
path: root/cmd/serve/serve.go
blob: 8591084d29700813c4ec0b7a850f27fa8653a31b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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)
	},
}