all repos

onasty @ f469c12

a one-time notes service

onasty/internal/transport/http/http.go(view raw)

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
68
69
70
71
72
73
74
package http

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/olexsmir/onasty/internal/config"
	"github.com/olexsmir/onasty/internal/service/notesrv"
	"github.com/olexsmir/onasty/internal/service/usersrv"
	"github.com/olexsmir/onasty/internal/transport/http/apiv1"
	"github.com/olexsmir/onasty/internal/transport/http/ratelimit"
	"github.com/olexsmir/onasty/internal/transport/http/reqid"
)

type Transport struct {
	usersrv usersrv.UserServicer
	notesrv notesrv.NoteServicer

	env    config.Environment
	domain string

	corsAllowedOrigins []string
	corsMaxAge         time.Duration
	ratelimitCfg       ratelimit.Config
	slowRatelimitCfg   ratelimit.Config
}

func NewTransport(
	us usersrv.UserServicer,
	ns notesrv.NoteServicer,
	env config.Environment,
	domain string,
	corsAllowedOrigins []string,
	corsMaxAge time.Duration,
	ratelimitCfg ratelimit.Config,
	slowRatelimitCfg ratelimit.Config,
) *Transport {
	return &Transport{
		usersrv:            us,
		notesrv:            ns,
		env:                env,
		domain:             domain,
		corsAllowedOrigins: corsAllowedOrigins,
		corsMaxAge:         corsMaxAge,
		ratelimitCfg:       ratelimitCfg,
		slowRatelimitCfg:   slowRatelimitCfg,
	}
}

func (t *Transport) Handler() http.Handler {
	r := gin.New()
	r.Use(
		gin.Recovery(),
		reqid.Middleware(),
		t.loggerMiddleware(),
		t.corsMiddleware(),
		ratelimit.MiddlewareWithConfig(t.ratelimitCfg),
	)

	api := r.Group("/api")
	{
		api.GET("/ping", t.pingHandler)
		apiv1.
			NewAPIV1(t.usersrv, t.notesrv, t.slowRatelimitCfg, t.env, t.domain).
			Routes(api.Group("/v1"))
	}

	return r.Handler()
}

func (*Transport) pingHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "pong"})
}