onasty/internal/transport/http/http.go (view raw)
Olexandr Smirnov
Olexandr Smirnov
ss2316544@gmail.com fix: use separate ratelimiter for some endpoints (#166)..., 10 months ago
ss2316544@gmail.com fix: use separate ratelimiter for some endpoints (#166)..., 10 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/notesrv" |
| 10 | "github.com/olexsmir/onasty/internal/service/usersrv" |
| 11 | "github.com/olexsmir/onasty/internal/transport/http/apiv1" |
| 12 | "github.com/olexsmir/onasty/internal/transport/http/ratelimit" |
| 13 | "github.com/olexsmir/onasty/internal/transport/http/reqid" |
| 14 | ) |
| 15 | |
| 16 | type Transport struct { |
| 17 | usersrv usersrv.UserServicer |
| 18 | notesrv notesrv.NoteServicer |
| 19 | |
| 20 | env config.Environment |
| 21 | domain string |
| 22 | |
| 23 | corsAllowedOrigins []string |
| 24 | corsMaxAge time.Duration |
| 25 | ratelimitCfg ratelimit.Config |
| 26 | slowRatelimitCfg ratelimit.Config |
| 27 | } |
| 28 | |
| 29 | func NewTransport( |
| 30 | us usersrv.UserServicer, |
| 31 | ns notesrv.NoteServicer, |
| 32 | env config.Environment, |
| 33 | domain string, |
| 34 | corsAllowedOrigins []string, |
| 35 | corsMaxAge time.Duration, |
| 36 | ratelimitCfg ratelimit.Config, |
| 37 | slowRatelimitCfg ratelimit.Config, |
| 38 | ) *Transport { |
| 39 | return &Transport{ |
| 40 | usersrv: us, |
| 41 | notesrv: ns, |
| 42 | env: env, |
| 43 | domain: domain, |
| 44 | corsAllowedOrigins: corsAllowedOrigins, |
| 45 | corsMaxAge: corsMaxAge, |
| 46 | ratelimitCfg: ratelimitCfg, |
| 47 | slowRatelimitCfg: slowRatelimitCfg, |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | func (t *Transport) Handler() http.Handler { |
| 52 | r := gin.New() |
| 53 | r.Use( |
| 54 | gin.Recovery(), |
| 55 | reqid.Middleware(), |
| 56 | t.loggerMiddleware(), |
| 57 | t.corsMiddleware(), |
| 58 | ratelimit.MiddlewareWithConfig(t.ratelimitCfg), |
| 59 | ) |
| 60 | |
| 61 | api := r.Group("/api") |
| 62 | { |
| 63 | api.GET("/ping", t.pingHandler) |
| 64 | apiv1. |
| 65 | NewAPIV1(t.usersrv, t.notesrv, t.slowRatelimitCfg, t.env, t.domain). |
| 66 | Routes(api.Group("/v1")) |
| 67 | } |
| 68 | |
| 69 | return r.Handler() |
| 70 | } |
| 71 | |
| 72 | func (*Transport) pingHandler(c *gin.Context) { |
| 73 | c.JSON(http.StatusOK, gin.H{"message": "pong"}) |
| 74 | } |