neko/internal/http/router.go

173 lines
4.0 KiB
Go
Raw Normal View History

2021-09-17 10:24:33 +12:00
package http
import (
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
2021-09-18 05:27:21 +12:00
"github.com/rs/zerolog"
"github.com/demodesk/neko/pkg/auth"
"github.com/demodesk/neko/pkg/types"
"github.com/demodesk/neko/pkg/utils"
2021-09-17 10:24:33 +12:00
)
type RouterOption func(*router)
func WithRequestID() RouterOption {
return func(r *router) {
r.chi.Use(middleware.RequestID)
}
}
func WithLogger(logger zerolog.Logger) RouterOption {
return func(r *router) {
r.chi.Use(middleware.RequestLogger(&logFormatter{logger}))
}
}
func WithRecoverer() RouterOption {
return func(r *router) {
r.chi.Use(middleware.Recoverer)
}
}
func WithCORS(allowOrigin func(origin string) bool) RouterOption {
return func(r *router) {
r.chi.Use(cors.Handler(cors.Options{
AllowOriginFunc: func(r *http.Request, origin string) bool {
return allowOrigin(origin)
},
AllowedMethods: []string{"GET", "POST", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
}))
}
}
func WithPathPrefix(prefix string) RouterOption {
return func(r *router) {
r.chi.Use(func(h http.Handler) http.Handler {
return http.StripPrefix(prefix, h)
})
}
}
func WithRealIP() RouterOption {
return func(r *router) {
r.chi.Use(middleware.RealIP)
}
}
2021-09-18 05:23:04 +12:00
type router struct {
2021-09-17 10:24:33 +12:00
chi chi.Router
}
func newRouter(opts ...RouterOption) types.Router {
r := &router{chi.NewRouter()}
for _, opt := range opts {
opt(r)
}
return r
2021-09-17 10:24:33 +12:00
}
2021-09-18 05:23:04 +12:00
func (r *router) Group(fn func(types.Router)) {
2021-09-17 10:24:33 +12:00
r.chi.Group(func(c chi.Router) {
2021-09-18 05:23:04 +12:00
fn(&router{c})
2021-09-17 10:24:33 +12:00
})
}
2021-09-18 05:23:04 +12:00
func (r *router) Route(pattern string, fn func(types.Router)) {
2021-09-17 10:24:33 +12:00
r.chi.Route(pattern, func(c chi.Router) {
2021-09-18 05:23:04 +12:00
fn(&router{c})
2021-09-17 10:24:33 +12:00
})
}
2021-09-18 05:23:04 +12:00
func (r *router) Get(pattern string, fn types.RouterHandler) {
2021-09-17 10:24:33 +12:00
r.chi.Get(pattern, routeHandler(fn))
}
2021-09-20 10:19:10 +12:00
2021-09-18 05:23:04 +12:00
func (r *router) Post(pattern string, fn types.RouterHandler) {
2021-09-17 10:24:33 +12:00
r.chi.Post(pattern, routeHandler(fn))
}
2021-09-20 10:19:10 +12:00
2021-09-18 05:23:04 +12:00
func (r *router) Put(pattern string, fn types.RouterHandler) {
2021-09-17 10:24:33 +12:00
r.chi.Put(pattern, routeHandler(fn))
}
2021-09-20 10:19:10 +12:00
2022-04-14 20:47:47 +12:00
func (r *router) Patch(pattern string, fn types.RouterHandler) {
r.chi.Patch(pattern, routeHandler(fn))
}
2021-09-18 05:23:04 +12:00
func (r *router) Delete(pattern string, fn types.RouterHandler) {
2021-09-17 10:24:33 +12:00
r.chi.Delete(pattern, routeHandler(fn))
}
2021-09-18 05:23:04 +12:00
func (r *router) With(fn types.MiddlewareHandler) types.Router {
2021-09-17 10:24:33 +12:00
c := r.chi.With(middlewareHandler(fn))
2021-09-18 05:23:04 +12:00
return &router{c}
2021-09-17 10:24:33 +12:00
}
2021-09-18 05:23:04 +12:00
func (r *router) Use(fn types.MiddlewareHandler) {
2021-09-17 10:24:33 +12:00
r.chi.Use(middlewareHandler(fn))
}
2021-09-20 10:19:10 +12:00
2021-09-18 05:23:04 +12:00
func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
2021-09-17 10:24:33 +12:00
r.chi.ServeHTTP(w, req)
}
func errorHandler(err error, w http.ResponseWriter, r *http.Request) {
httpErr, ok := err.(*utils.HTTPError)
if !ok {
httpErr = utils.HttpInternalServerError().WithInternalErr(err)
}
utils.HttpJsonResponse(w, httpErr.Code, httpErr)
}
func routeHandler(fn types.RouterHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2021-09-18 05:22:49 +12:00
// get custom log entry pointer from context
logEntry, _ := r.Context().Value(middleware.LogEntryCtxKey).(*logEntry)
2021-09-17 10:24:33 +12:00
if err := fn(w, r); err != nil {
2021-09-18 06:20:10 +12:00
logEntry.Error(err)
2021-09-17 10:24:33 +12:00
errorHandler(err, w, r)
}
2021-09-18 05:22:49 +12:00
// set session if exits
if session, ok := auth.GetSession(r); ok {
logEntry.SetSession(session)
}
2021-09-17 10:24:33 +12:00
}
}
func middlewareHandler(fn types.MiddlewareHandler) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2021-09-18 05:22:49 +12:00
// get custom log entry pointer from context
logEntry, _ := r.Context().Value(middleware.LogEntryCtxKey).(*logEntry)
2021-09-17 10:24:33 +12:00
ctx, err := fn(w, r)
if err != nil {
2021-09-18 06:20:10 +12:00
logEntry.Error(err)
2021-09-17 10:24:33 +12:00
errorHandler(err, w, r)
2021-09-18 05:22:49 +12:00
// set session if exits
if session, ok := auth.GetSession(r); ok {
logEntry.SetSession(session)
}
2021-09-17 10:24:33 +12:00
return
}
if ctx != nil {
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
}