thedevsaddam / govalidator

Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.
MIT License
1.31k stars 124 forks source link

Can I use this with Echo? #123

Open canaan5 opened 10 months ago

canaan5 commented 10 months ago

Can I use this with Echo?

Kirari04 commented 4 months ago

Yes you can.

Code Example

package main

import (
    "fmt"
    "net/http"
    "strings"

    "github.com/labstack/echo/v4"
    "github.com/thedevsaddam/govalidator"
)

type Params struct {
    Name string `query:"name" json:"name" form:"name"`
}

func main() {
    e := echo.New()
    e.GET("/", func(c echo.Context) error {
        var u Params
        if err := c.Bind(&u); err != nil {
            return echo.NewHTTPError(http.StatusBadRequest, "failed to bind params")
        }
        opts := govalidator.Options{
            Data: &u,
            Rules: govalidator.MapData{
                "name": []string{"required", "between:2,10"},
            },
            Messages: govalidator.MapData{
                "name": []string{"required:Name cant be empty", "between:name needs to be between 2 and 10 characters"},
            },
            RequiredDefault: true,
        }
        v := govalidator.New(opts)
        e := v.ValidateStruct()
        if len(e) > 0 {
            for k, v := range e {
                return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("%s: %s", k, strings.Join(v, ", ")))
            }
            return echo.NewHTTPError(http.StatusBadRequest, "unknown error during validation")
        }

        return c.String(http.StatusOK, fmt.Sprintf("Hi %s", u.Name))
    })
    e.Logger.Fatal(e.Start(":1323"))
}

Result Examples

GET http://127.0.0.1:1323/
{"message":"name: Name cant be empty, name needs to be between 2 and 10 characters"}

GET http://127.0.0.1:1323/?name=A
{"message":"name: name needs to be between 2 and 10 characters"}

GET http://127.0.0.1:1323/?name=ABC
Hi ABC

Full Example https://github.com/Kirari04/echo-govalidator-example