all repos

onasty @ 757b945

a one-time notes service

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

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
feat: add cors (#115)..., 1 year 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/service/notesrv"
9
	"github.com/olexsmir/onasty/internal/service/usersrv"
10
	"github.com/olexsmir/onasty/internal/transport/http/apiv1"
11
	"github.com/olexsmir/onasty/internal/transport/http/ratelimit"
12
	"github.com/olexsmir/onasty/internal/transport/http/reqid"
13
)
14
15
type Transport struct {
16
	usersrv usersrv.UserServicer
17
	notesrv notesrv.NoteServicer
18
19
	corsAllowedOrigins []string
20
	corsMaxAge         time.Duration
21
	ratelimitCfg       ratelimit.Config
22
}
23
24
func NewTransport(
25
	us usersrv.UserServicer,
26
	ns notesrv.NoteServicer,
27
	corsAllowedOrigins []string,
28
	corsMaxAge time.Duration,
29
	ratelimitCfg ratelimit.Config,
30
) *Transport {
31
	return &Transport{
32
		usersrv:            us,
33
		notesrv:            ns,
34
		corsAllowedOrigins: corsAllowedOrigins,
35
		corsMaxAge:         corsMaxAge,
36
		ratelimitCfg:       ratelimitCfg,
37
	}
38
}
39
40
func (t *Transport) Handler() http.Handler {
41
	r := gin.New()
42
	r.Use(
43
		gin.Recovery(),
44
		reqid.Middleware(),
45
		t.loggerMiddleware(),
46
		t.corsMiddleware(),
47
		ratelimit.MiddlewareWithConfig(t.ratelimitCfg),
48
	)
49
50
	api := r.Group("/api")
51
	api.GET("/ping", t.pingHandler)
52
	apiv1.NewAPIV1(t.usersrv, t.notesrv).Routes(api.Group("/v1"))
53
54
	return r.Handler()
55
}
56
57
func (*Transport) pingHandler(c *gin.Context) {
58
	c.JSON(http.StatusOK, gin.H{"message": "pong"})
59
}