govalidator icon indicating copy to clipboard operation
govalidator copied to clipboard

Invalid Read on closed Body

Open ziasultan2 opened this issue 1 year ago • 0 comments

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)
}

ziasultan2 avatar Oct 18 '23 07:10 ziasultan2