yudhiesh
yudhiesh

Reputation: 6799

Correct request body is deemed to be invalid by validator in Go

I am trying to validate the request body according to this struct using validator. But in Postman it always throws an error when validating the struct. I just want all values to be required when making a request.

package model

type User struct {
    FeatureName string `json:"featureName" validate:"required"`
    Email       string `json:"email" validate:"required"`
    CanAccess   *bool  `json:"can_access" validate:"required"`
}

I have tried sending this as the request body on Postman:

// Request body
{
    "featureName": "crypto",
    "email": "[email protected]",
    "can_access": true
}

// Response body
{
    "status": 422,
    "message": "Missing parameters featureName/can_access/email"
}

Code:

package controller

import (
    "database/sql"
    "encoding/json"
    "errors"
    "net/http"
    "unicode/utf8"

    "github.com/yudhiesh/api/model"
    "gopkg.in/validator.v2"

    "github.com/yudhiesh/api/config"
)

func InsertFeature(w http.ResponseWriter, r *http.Request) {
    var user model.User
    var response model.Response

    db := config.Connect()
    defer db.Close()

    // Decode body into user struct
    if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
        response.Message = "Error"
        response.Status = http.StatusInternalServerError
        json.NewEncoder(w).Encode(response)
        return
    } else {
        // Validate struct to check if all fields are correct
        // Fails here!
        if err := validator.Validate(user); err != nil {
            response.Message = "Missing parameters featureName/can_access/email"
            response.Status = http.StatusUnprocessableEntity
            json.NewEncoder(w).Encode(response)
            return
        } else {
            // Execute insert statement to database
            stmt := `INSERT INTO features (user_id, feature_name, can_access) SELECT id, ?, ? FROM users WHERE email=?`
            if _, err = db.Exec(stmt, &user.FeatureName, &user.CanAccess, &user.Email); err != nil {
                response.Message = "Error"
                response.Status = http.StatusInternalServerError
                json.NewEncoder(w).Encode(response)
                return
            } else {
                response.Message = "Success"
                response.Status = http.StatusOK
                json.NewEncoder(w).Encode(response)
                return
            }

        }

    }

}

Upvotes: 0

Views: 811

Answers (1)

Key_coder
Key_coder

Reputation: 536

Moving Comment to answer

I see a problem in your code the link you have shared is https://github.com/go-playground/validator but in the code, import is gopkg.in/validator.v2 If you are using the go-playground validator Use below code to validate

import https://github.com/go-playground/validator

validatorInstance:=validator.New()
validatorInstance.Struct(user)

Upvotes: 1

Related Questions