all repos

onasty @ ac9bab3

a one-time notes service

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

Olexandr Smirnov Olexandr Smirnov
olexsmir@gmail.com
refactor(api): split `usersrv` responsibilities (#195)..., 9 months ago
1
package http
2
3
import (
4
	"net/http"
5
	"time"
6
7
	"github.com/gin-gonic/gin"
8
	"github.com/olexsmir/onasty/internal/config"
9
	"github.com/olexsmir/onasty/internal/service/authsrv"
10
	"github.com/olexsmir/onasty/internal/service/notesrv"
11
	"github.com/olexsmir/onasty/internal/service/usersrv"
12
	"github.com/olexsmir/onasty/internal/transport/http/apiv1"
13
	"github.com/olexsmir/onasty/internal/transport/http/ratelimit"
14
	"github.com/olexsmir/onasty/internal/transport/http/reqid"
15
)
16
17
type Transport struct {
18
	authsrv authsrv.AuthServicer
19
	usersrv usersrv.UserServicer
20
	notesrv notesrv.NoteServicer
21
22
	env    config.Environment
23
	domain string
24
25
	corsAllowedOrigins []string
26
	corsMaxAge         time.Duration
27
	ratelimitCfg       ratelimit.Config
28
	slowRatelimitCfg   ratelimit.Config
29
}
30
31
func NewTransport(
32
	as authsrv.AuthServicer,
33
	us usersrv.UserServicer,
34
	ns notesrv.NoteServicer,
35
	env config.Environment,
36
	domain string,
37
	corsAllowedOrigins []string,
38
	corsMaxAge time.Duration,
39
	ratelimitCfg ratelimit.Config,
40
	slowRatelimitCfg ratelimit.Config,
41
) *Transport {
42
	return &Transport{
43
		authsrv:            as,
44
		usersrv:            us,
45
		notesrv:            ns,
46
		env:                env,
47
		domain:             domain,
48
		corsAllowedOrigins: corsAllowedOrigins,
49
		corsMaxAge:         corsMaxAge,
50
		ratelimitCfg:       ratelimitCfg,
51
		slowRatelimitCfg:   slowRatelimitCfg,
52
	}
53
}
54
55
func (t *Transport) Handler() http.Handler {
56
	r := gin.New()
57
	r.Use(
58
		gin.Recovery(),
59
		reqid.Middleware(),
60
		t.loggerMiddleware(),
61
		t.corsMiddleware(),
62
		ratelimit.MiddlewareWithConfig(t.ratelimitCfg),
63
	)
64
65
	api := r.Group("/api")
66
	{
67
		api.GET("/ping", t.pingHandler)
68
		apiv1.
69
			NewAPIV1(t.authsrv, t.usersrv, t.notesrv, t.slowRatelimitCfg, t.env, t.domain).
70
			Routes(api.Group("/v1"))
71
	}
72
73
	return r.Handler()
74
}
75
76
func (*Transport) pingHandler(c *gin.Context) {
77
	c.JSON(http.StatusOK, gin.H{"message": "pong"})
78
}