govalidator
govalidator copied to clipboard
Invalid Read on closed Body
Getting this error when try to read Request after validation {"error": "http: invalid Read on closed Body"}
When try to use c.ShouldBindJSON(&dept) in Controller function
Request function
func CreateDepartment(request *http.Request) url.Values {
rules := govalidator.MapData{
"name": []string{"required", "between:3,20"},
"description": []string{"required", "min:10", "max:255"},
}
type Department struct {
Name string `json:"name"`
Description string `json:"description"`
Slug string `json:"slug"`
}
var department Department
opts := govalidator.Options{
Request: request,
Rules: rules,
Data: &department,
}
v := govalidator.New(opts)
v.SetTagIdentifier("json")
e := v.ValidateJSON()
return e
}
Controller function
func createDepartment(c *gin.Context) {
validationError := request.CreateDepartment(c.Request)
if len(validationError) != 0 {
c.JSON(http.StatusBadRequest, validationError)
return
}
var dept department.Department
fmt.Println("after validation")
if err := c.ShouldBindJSON(&dept); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err := service.CreateDepartment(&dept)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Couldn't create department",
})
return
}
c.JSON(http.StatusOK, dept)
}