Dump changes

This commit is contained in:
Andrey Chervyakov 2022-06-03 23:44:08 +06:00
parent e12550a643
commit aac2ea1b74
Signed by: cognio
GPG key ID: DAA316147EB0D58D
25 changed files with 129 additions and 76 deletions

View file

@ -0,0 +1,34 @@
package server
import (
"github.com/labstack/echo/v4"
"github.com/rs/zerolog/log"
"time"
)
func Logger() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
req := c.Request()
res := c.Response()
start := time.Now()
if err = next(c); err != nil {
c.Error(err)
}
stop := time.Now()
log.Info().
Str("remote_ip", c.RealIP()).
Str("host", req.Host).
Str("uri", req.RequestURI).
Str("method", req.Method).
Str("path", req.URL.Path).
Str("user_agent", req.UserAgent()).
Int("status", res.Status).
Str("latency", stop.Sub(start).String()).
Send()
return
}
}
}

View file

@ -0,0 +1,61 @@
package server
import (
"brainbuffer/pkg/brainbuffer/domain/task"
"brainbuffer/pkg/brainbuffer/infrastructure"
apperrors "brainbuffer/pkg/brainbuffer/infrastructure/errors"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/knadh/koanf"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/rs/zerolog/log"
"net/http"
)
func New(context *infrastructure.Context) *echo.Echo {
server := echo.New()
server.HTTPErrorHandler = errorHandler(server)
registerHandlers(server, context.Database)
registerMiddleware(server, context.Config)
return server
}
func registerHandlers(server *echo.Echo, pool *pgxpool.Pool) {
task.AddHandlers(server)
}
func registerMiddleware(server *echo.Echo, conf *koanf.Koanf) {
server.Use(middleware.CORS())
server.Use(Logger())
server.Use(middleware.JWTWithConfig(middleware.JWTConfig{
Skipper: func(ctx echo.Context) bool {
return false
},
SigningMethod: middleware.AlgorithmHS256,
SigningKey: conf.Bytes("jwt.key"),
}))
}
func errorHandler(s *echo.Echo) echo.HTTPErrorHandler {
return func(err error, c echo.Context) {
mappedErr := err
switch v := err.(type) {
case apperrors.NotFoundError:
mappedErr = echo.NewHTTPError(http.StatusNotFound, v.Error())
case apperrors.UnknownError:
log.Err(v.Err).Send()
mappedErr = echo.NewHTTPError(http.StatusInternalServerError)
case apperrors.AlreadyExistsError:
// TODO: Change status code to hide user identity.
mappedErr = echo.NewHTTPError(http.StatusBadRequest, v.Error())
}
s.DefaultHTTPErrorHandler(mappedErr, c)
}
}