This commit is contained in:
Andrey Chervyakov 2021-03-17 18:54:45 +06:00
parent e426559cec
commit ddaf0dcbfc
6 changed files with 42 additions and 40 deletions

34
server/middleware.go Normal file
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
}
}
}

70
server/server.go Normal file
View file

@ -0,0 +1,70 @@
package server
import (
apperrors "cgnolink/errors"
"cgnolink/link"
"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"
"regexp"
)
func NewServer(conf *koanf.Koanf, pool *pgxpool.Pool) *echo.Echo {
server := echo.New()
server.HTTPErrorHandler = errorHandler(server)
addMiddleware(server, conf)
addHandlers(server, pool)
return server
}
func addMiddleware(s *echo.Echo, conf *koanf.Koanf) {
s.Use(middleware.CORS())
s.Use(Logger())
s.Use(middleware.JWTWithConfig(middleware.JWTConfig{
Skipper: func(ctx echo.Context) bool {
matchesLinks, _ := regexp.MatchString("^/links", ctx.Request().URL.Path)
return ctx.Request().Method == "GET" && !matchesLinks
},
SigningMethod: conf.String("jwt.method"),
SigningKey: conf.Bytes("jwt.key"),
}))
}
func addHandlers(s *echo.Echo, pool *pgxpool.Pool) {
s.GET("", func(ctx echo.Context) error {
return ctx.JSON(http.StatusOK, struct {
Message string `json:"message"`
}{
Message: "Hello. This is my (https://cognio.dev/) URL shortener for easy access to my socials, projects and other resources.",
})
})
link.AddHandlers(s, pool)
}
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:
mappedErr = echo.NewHTTPError(http.StatusBadRequest, v.Error())
}
s.DefaultHTTPErrorHandler(mappedErr, c)
}
}