Skip to content

Invalid Read on closed Body #122

@ziasultan2

Description

@ziasultan2

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions