https:\/\/pkg.go.dev\/github.com\/go-playground\/validator<\/a><\/li><\/ul>\n\n\n\nFor this tutorial, we will try to parse the incoming JSON request body into the below employee struct<\/p>\n\n\n\n
type employee struct {\n Age int `validate:\"required,gte=10,lte=20\"`\n}<\/code><\/pre>\n\n\n\nNotice here that we need to associate meta tags with fields of the struct to let the validator know that you want to validate this field. In the above example, we added the tag with the Age field. This tag is interpreted by the playground validate library. Notice we added three validations for the Age<\/strong> field<\/p>\n\n\n\nrequired<\/strong> – validates that the field is present<\/li><\/ul>\n\n\n\ngte<\/strong> – validate that the field value is greater than equal to a particular value<\/li><\/ul>\n\n\n\nlte<\/strong> – validate that the field value is less than equal to a particular value<\/li><\/ul>\n\n\n\n<\/span>Program<\/strong><\/span><\/h1>\n\n\n\npackage main\nimport (\n \"encoding\/json\"\n \"net\/http\"\n \"github.com\/go-playground\/validator\"\n)\nvar validate *validator.Validate\ntype employee struct {\n Age int `validate:\"required,gte=10,lte=20\"`\n}\nfunc main() {\n createEmployeeHanlder := http.HandlerFunc(createEmployee)\n http.Handle(\"\/employee\", createEmployeeHanlder)\n http.ListenAndServe(\":8080\", nil)\n}\nfunc createEmployee(w http.ResponseWriter, r *http.Request) {\n headerContentTtype := r.Header.Get(\"Content-Type\")\n if headerContentTtype != \"application\/json\" {\n errorResponse(w, \"Content Type is not application\/json\", http.StatusUnsupportedMediaType)\n return\n }\n var e employee\n decoder := json.NewDecoder(r.Body)\n err := decoder.Decode(&e)\n if err != nil {\n errorResponse(w, \"Bad Request \"+err.Error(), http.StatusBadRequest)\n }\n err = validateStruct(e)\n if err != nil {\n errorResponse(w, \"Bad Request \"+err.Error(), http.StatusBadRequest)\n }\n errorResponse(w, \"Success\", http.StatusOK)\n return\n}\nfunc errorResponse(w http.ResponseWriter, message string, httpStatusCode int) {\n w.Header().Set(\"Content-Type\", \"application\/json\")\n w.WriteHeader(httpStatusCode)\n resp := make(map[string]string)\n resp[\"message\"] = message\n jsonResp, _ := json.Marshal(resp)\n w.Write(jsonResp)\n}\nfunc validateStruct(e employee) error {\n validate = validator.New()\n err := validate.Struct(e)\n if err != nil {\n return err\n }\n return nil\n}<\/code><\/pre>\n\n\n\nRun the program. <\/p>\n\n\n\n
go run main.go<\/code><\/pre>\n\n\n\nIt will start an HTTP server listening on port 8080. Now make some curl API calls<\/p>\n\n\n\n
Below curl call<\/li><\/ul>\n\n\n\ncurl -X POST -H \"content-type: application\/json\" http:\/\/localhost:8080\/employee -d '{\"Age\": 5}'<\/code><\/pre>\n\n\n\ngives below response as 5 is less than the minimum which is 10<\/p>\n\n\n\n
{\"message\":\"Bad Request Key: 'employee.Age' Error:Field validation for 'Age' failed on the 'gte' tag\"}<\/code><\/pre>\n\n\n\nBelow curl call<\/li><\/ul>\n\n\n\ncurl -X POST -H \"content-type: application\/json\" http:\/\/localhost:8080\/employee -d '{\"Age\": 10}'<\/code><\/pre>\n\n\n\ngives below response as 10 is greater than the maximum which is 20<\/p>\n\n\n\n
{\"message\":\"Bad Request Key: 'employee.Age' Error:Field validation for 'Age' failed on the 'lte' tag\"}<\/code><\/pre>\n\n\n\nBelow curl call<\/li><\/ul>\n\n\n\ncurl -X POST -H \"content-type: application\/json\" http:\/\/localhost:8080\/employee -d '{\"Age\": 15}'<\/code><\/pre>\n\n\n\ngives response as success as 15 is greater than 10 and less than 20.<\/p>\n\n\n\n
{\"message\":\"Success\"}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"Table of Contents OverviewProgram Overview The below library can be used to validate the range of an integer in an incoming JSON HTTP request body gopkg.in\/go-playground\/validator.v9 – https:\/\/pkg.go.dev\/github.com\/go-playground\/validator For this tutorial, we…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[],"class_list":["post-5190","post","type-post","status-publish","format-standard","hentry","category-tech"],"yoast_head":"\n
Validate the range of the integer in an HTTP request body in Go (Golang) - Welcome To Golang By Example<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n