How to validate JSON input

anshuraj picture anshuraj · May 30, 2019 · Viewed 12.8k times · Source

I'm using Beego framework to build a web application in Go. I have to validate the incoming JSON in an API request.

I can unmarshal the JSON into a struct which works fine, but I want to validate the data as well. For example, if the type doesn't match with the type in struct json.Unmarshal will reutrn an error on the first occurence. I want to validate and get all the errors at once for JSON.

I've tried https://github.com/thedevsaddam/govalidator but the package needs a reference to request object which is not available in the controller of Beego. There are other validators which can validate a struct but i want the json validation as well.

EDIT:

A reference to the request object in beego can be found from the controller's context object as:

func (this *MainController) Post() {
    fmt.Println(this.Ctx.Request)
}

But the problem remains same with json unmarshal. If there's any slight mismatch in the type, json.unmarshal will immediately panic. I want to be able to validate the type as well.

Answer

Nestor Sokil picture Nestor Sokil · May 30, 2019

We've used go-playground/validator.v8 for a similar purpose. You can define the data validations with the tags that come out of the box (basic stuff like equality, min/max and even has somthing of an expression lang). On top of that you can add your custom validations. It's all in the docs, hope it helps.