68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
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"
|
|
)
|
|
|
|
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 {
|
|
return ctx.Request().Method == "GET" && ctx.Request().URL.Path != "/links"
|
|
},
|
|
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)
|
|
}
|
|
}
|