onasty/internal/transport/http/http.go (view raw)
| 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 | } |
| 27 | |
| 28 | func NewTransport( |
| 29 | us usersrv.UserServicer, |
| 30 | ns notesrv.NoteServicer, |
| 31 | env config.Environment, |
| 32 | domain string, |
| 33 | corsAllowedOrigins []string, |
| 34 | corsMaxAge time.Duration, |
| 35 | ratelimitCfg ratelimit.Config, |
| 36 | ) *Transport { |
| 37 | return &Transport{ |
| 38 | usersrv: us, |
| 39 | notesrv: ns, |
| 40 | env: env, |
| 41 | domain: domain, |
| 42 | corsAllowedOrigins: corsAllowedOrigins, |
| 43 | corsMaxAge: corsMaxAge, |
| 44 | ratelimitCfg: ratelimitCfg, |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | func (t *Transport) Handler() http.Handler { |
| 49 | r := gin.New() |
| 50 | r.Use( |
| 51 | gin.Recovery(), |
| 52 | reqid.Middleware(), |
| 53 | t.loggerMiddleware(), |
| 54 | t.corsMiddleware(), |
| 55 | ratelimit.MiddlewareWithConfig(t.ratelimitCfg), |
| 56 | ) |
| 57 | |
| 58 | api := r.Group("/api") |
| 59 | api.GET("/ping", t.pingHandler) |
| 60 | apiv1.NewAPIV1(t.usersrv, t.notesrv, t.env, t.domain).Routes(api.Group("/v1")) |
| 61 | |
| 62 | return r.Handler() |
| 63 | } |
| 64 | |
| 65 | func (*Transport) pingHandler(c *gin.Context) { |
| 66 | c.JSON(http.StatusOK, gin.H{"message": "pong"}) |
| 67 | } |