Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid Read on closed Body #122

Open
ziasultan2 opened this issue Oct 18, 2023 · 0 comments
Open

Invalid Read on closed Body #122

ziasultan2 opened this issue Oct 18, 2023 · 0 comments

Comments

@ziasultan2
Copy link

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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant