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

63 lines
1.3 KiB
Go

package v1
import (
"fmt"
"go-cook/api/models"
"net/http"
"github.com/labstack/echo/v4"
)
type HelloWhoResponse struct {
Success bool `json:"success"`
Error string `error:"error"`
Message string `json:"message"`
}
func (h *Handler) DemoHello(c echo.Context) error {
return c.JSON(http.StatusOK, HelloWhoResponse{
Success: true,
Message: "Hello world!",
})
}
func (h *Handler) HelloWho(c echo.Context) error {
name := c.Param("who")
return c.JSON(http.StatusOK, HelloWhoResponse{
Success: true,
Message: fmt.Sprintf("Hello, %s", name),
})
}
type HelloBodyRequest struct {
Name string `json:"name" validate:"required"`
}
func (h *Handler) HelloBody(c echo.Context) error {
request := HelloBodyRequest{}
err := (&echo.DefaultBinder{}).BindBody(c, &request)
if err != nil {
return c.JSON(http.StatusBadRequest, HelloWhoResponse{
Success: false,
Error: err.Error(),
})
}
return c.JSON(http.StatusOK, HelloWhoResponse{
Success: true,
Message: fmt.Sprintf("Hello, %s", request.Name),
})
}
func (h *Handler) ProtectedRoute(c echo.Context) error {
token, err := h.getJwtToken(c)
if err != nil {
return c.JSON(http.StatusForbidden, models.ErrorResponse{
HttpCode: http.StatusForbidden,
Message: err.Error(),
})
}
return c.JSON(http.StatusOK, token)
}