aboutsummaryrefslogtreecommitdiff
path: root/cmd/app/serve/serve.go
blob: 060908333afe95bbfd5e0329dae2ccd9a7f426ac (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
package serve

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/ssoda/captcha"
	"github.com/uptrace/bun/extra/bundebug"
	"github.com/urfave/cli/v2"
	"sh.org.ru/pkg/config"
	"sh.org.ru/pkg/db"
	"sh.org.ru/pkg/handler"
	"sh.org.ru/static"
)

func Run(c *cli.Context) error {
	configFile := c.String("config")
	cfg, err := config.New(configFile)
	if err != nil {
		return err
	}
	db := db.New(cfg.DB)
	db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(cfg.Debug)))

	h := handler.Handler{DB: db}

	e := echo.New()

	e.HTTPErrorHandler = handler.ErrorHandler

	e.Use(middleware.Recover())
	e.Use(middleware.Logger())

	e.GET("/", h.Index)
	e.GET("/quote/:id", h.Quote)
	e.GET("/random", h.Random)
	e.GET("/add", h.AddQuote)
	e.POST("/add", h.AddQuotePost)
	e.GET("/add/success", h.AddQuoteSuccess)
	e.GET("/captcha/*", echo.WrapHandler(captcha.Server(400, 65)))

	func(g *echo.Group) {
		g.GET("/", h.Admin)
		g.POST("/action", h.AdminAction)
	}(e.Group("/admin", middleware.BasicAuth(func(u, p string, ctx echo.Context) (bool, error) {
		return cfg.Admins[u] == p, nil
	})))

	e.StaticFS("/", static.FS)

	return e.Start(cfg.Listen)
}