Created
October 17, 2023 04:08
-
-
Save linxlunx/7347e40b4643d76f6a31dfc8112d85b3 to your computer and use it in GitHub Desktop.
Go Echo with Validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"github.com/go-playground/validator/v10" | |
"github.com/labstack/echo/v4" | |
) | |
type UserDetail struct { | |
Email string `json:"email" validate:"required,email"` | |
Age int `json:"age" validate:"required,gte=18"` | |
} | |
type CustomValidator struct { | |
validator *validator.Validate | |
} | |
func (cv *CustomValidator) Validate(i interface{}) error { | |
if err := cv.validator.Struct(i); err != nil { | |
return echo.NewHTTPError(http.StatusBadRequest, err.Error()) | |
} | |
return nil | |
} | |
func main() { | |
e := echo.New() | |
e.Validator = &CustomValidator{validator: validator.New()} | |
e.GET("/", func(c echo.Context) error { | |
return c.JSON(http.StatusOK, map[string]string{"message": "hai"}) | |
}) | |
e.POST("/", func(c echo.Context) error { | |
userData := new(UserDetail) | |
if err := c.Bind(userData); err != nil { | |
return c.JSON(http.StatusPreconditionFailed, map[string]string{"error": err.Error()}) | |
} | |
if err := c.Validate(userData); err != nil { | |
return c.JSON(http.StatusPreconditionFailed, map[string]string{"error": err.Error()}) | |
} | |
return c.JSON(http.StatusOK, map[string]string{"message":"passed"}) | |
}) | |
e.Logger.Fatal(e.Start(":5000")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment