go-cook/api/handlers/v1/handler.go

75 lines
1.8 KiB
Go
Raw Normal View History

package v1
import (
"database/sql"
"go-cook/api/domain"
"go-cook/api/repositories"
"go-cook/api/services"
"net/http"
"github.com/golang-jwt/jwt/v5"
echojwt "github.com/labstack/echo-jwt/v4"
"github.com/labstack/echo/v4"
)
type Handler struct {
Config domain.EnvConfig
UserService services.UserService
userRepo repositories.IUserTable
recipeRepo repositories.IRecipeTable
}
func NewHandler(conn *sql.DB, cfg domain.EnvConfig) *Handler {
return &Handler{
Config: cfg,
UserService: services.NewUserService(conn),
userRepo: repositories.NewUserRepository(conn),
recipeRepo: repositories.NewRecipeRepository(conn),
}
}
func (h *Handler) Register(v1 *echo.Group) {
jwtConfig := echojwt.Config{
NewClaimsFunc: func(c echo.Context) jwt.Claims {
return new(JwtToken)
},
SigningKey: []byte(h.Config.JwtSecret),
}
v1.POST("/login", h.AuthLogin)
v1.POST("/register", h.AuthRegister)
demo := v1.Group("/demo")
demo.GET("/hello", h.DemoHello)
demo.GET("/hello/:who", h.HelloWho)
demo.Use(echojwt.WithConfig(jwtConfig))
demo.GET("/hello/body", h.HelloBody)
protected := v1.Group("/demo/protected")
protected.Use(echojwt.WithConfig(jwtConfig))
protected.GET("", h.ProtectedRoute)
//recipes := v1.Group("/recipe")
//users := v1.Group("/users")
//users.POST("/register", h.RegisterUser)
//users.POST("/login", h.LoginUser)
//users.POST("/update/password", h.UpdatePassword)
}
func (h *Handler) ReturnUnauthorizedResponse(c echo.Context, message string) error {
return c.JSON(http.StatusUnauthorized, domain.ErrorResponse{
HttpCode: http.StatusUnauthorized,
Message: message,
})
}
func (h *Handler) InternalServerErrorResponse(c echo.Context, message string) error {
return c.JSON(http.StatusServiceUnavailable, domain.ErrorResponse{
HttpCode: http.StatusInternalServerError,
Message: message,
})
}