all repos

onasty @ dependabot/github_actions/marocchino/tool-versions-action-2

a one-time notes service

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

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
feat(web): add oauth login (#213)..., 8 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
	appURL      string
24
	frontendURL string
25
26
	corsAllowedOrigins []string
27
	corsMaxAge         time.Duration
28
	ratelimitCfg       ratelimit.Config
29
	slowRatelimitCfg   ratelimit.Config
30
}
31
32
func NewTransport(
33
	as authsrv.AuthServicer,
34
	us usersrv.UserServicer,
35
	ns notesrv.NoteServicer,
36
	env config.Environment,
37
	appURL, frontendURL string,
38
	corsAllowedOrigins []string,
39
	corsMaxAge time.Duration,
40
	ratelimitCfg ratelimit.Config,
41
	slowRatelimitCfg ratelimit.Config,
42
) *Transport {
43
	return &Transport{
44
		authsrv:            as,
45
		usersrv:            us,
46
		notesrv:            ns,
47
		env:                env,
48
		appURL:             appURL,
49
		frontendURL:        frontendURL,
50
		corsAllowedOrigins: corsAllowedOrigins,
51
		corsMaxAge:         corsMaxAge,
52
		ratelimitCfg:       ratelimitCfg,
53
		slowRatelimitCfg:   slowRatelimitCfg,
54
	}
55
}
56
57
func (t *Transport) Handler() http.Handler {
58
	r := gin.New()
59
	r.Use(
60
		gin.Recovery(),
61
		reqid.Middleware(),
62
		t.loggerMiddleware(),
63
		t.corsMiddleware(),
64
		ratelimit.MiddlewareWithConfig(t.ratelimitCfg),
65
	)
66
67
	api := r.Group("/api")
68
	{
69
		api.GET("/ping", t.pingHandler)
70
		apiv1.
71
			NewAPIV1(
72
				t.authsrv,
73
				t.usersrv,
74
				t.notesrv,
75
				t.slowRatelimitCfg,
76
				t.env,
77
				t.appURL,
78
				t.frontendURL,
79
			).
80
			Routes(api.Group("/v1"))
81
	}
82
83
	return r.Handler()
84
}
85
86
func (*Transport) pingHandler(c *gin.Context) {
87
	c.JSON(http.StatusOK, gin.H{"message": "pong"})
88
}