How to Ensure Required Fields Presence and Validate HTTP Request with Echo Framework?

259 views Asked by At

Is there a anyway to validate if a field is present in a http request with the echo framwork?

Lets take this code for example:

type ExampleStruct struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}
func main() {
    e := echo.New()
    // POST endpoint to demonstrate c.Bind
    e.POST("/example", func(c echo.Context) error {
        var requestData ExampleStruct
        if err := c.Bind(&requestData); err != nil {
            // Handle binding error
            return c.JSON(http.StatusBadRequest, map[string]string{"error": "Failed to bind request body"})
        }
        name := requestData.Name
        email := requestData.Email
        return c.JSON(http.StatusOK, map[string]string{"message": "Request body bound successfully", "name": name, "email": email})
    })
    e.Start(":8080")
}

And this is the post request from the client side:

curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe"}' http://localhost:8080/example

In this example the email is missing in the request and my goal is return a http error that the field is missing. Currently if a field isn't set, the echo Bind function just takes the default zero value for that field and binds it to the struct and thats not what I want.

Whats the best practice to return an error if a field isn't set or present.

0

There are 0 answers