Refactor
This commit is contained in:
parent
e426559cec
commit
ddaf0dcbfc
6 changed files with 42 additions and 40 deletions
71
server.go
71
server.go
|
|
@ -1,71 +0,0 @@
|
|||
package cgnolink
|
||||
|
||||
import (
|
||||
apperrors "cgnolink/errors"
|
||||
"cgnolink/link"
|
||||
appmiddleware "cgnolink/middleware"
|
||||
"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(appmiddleware.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)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue