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

Validating request body always returns error #56

Closed
CodebyOmar opened this issue Jan 28, 2019 · 2 comments
Closed

Validating request body always returns error #56

CodebyOmar opened this issue Jan 28, 2019 · 2 comments

Comments

@CodebyOmar
Copy link

I'm trying to use govalidator and it always returns error even if i send the correct data, may i'm doing it wrong because this is my first time using this package.

package notifier

import (
	"encoding/json"
	"net/http"

	"github.com/thedevsaddam/govalidator"
)

// Payload is request data structure expected
type Payload struct {
	TransactionReference    string              `json:"transactionReference"`
	Timestamp                    string               `json:"timestamp"`
	ItemID                           string               `json:"itemId"`
	AmountPaid                  govalidator.Int `json:"amountPaid"`
	Status                            string               `json:"status"`
}

type res struct {
	Message string `json:"message"`
	Data    *Payload
}

// UpdatePayment Receives payment details and sends to accounting API
func UpdatePayment(w http.ResponseWriter, r *http.Request) {
	p := new(Payload)

	opts := govalidator.Options{
		Request:         r,
		Data:            &p,
		Rules:           rules,
		RequiredDefault: true,
	}

	req := govalidator.New(opts)
	e := req.Validate()

	if len(e) > 0 {
		validationErr := map[string]interface{}{"data": e, "status": "error"}
		json.NewEncoder(w).Encode(validationErr)
		return
	}

	retMsg := &res{
		Message: "Payment notification recieved",
		Data:    p,
	}

	json.NewEncoder(w).Encode(retMsg)
}

second file valitadions.go

package notifier

import "github.com/thedevsaddam/govalidator"

var rules = govalidator.MapData{
	"amountPaid":                  []string{"required", "numeric"},
	"timestamp":                    []string{"required", "date"},
	"transactionReference":   []string{"required"},
	"itemId":                          []string{"required"},
	"status":                           []string{"required"},
}
@CodebyOmar
Copy link
Author

CodebyOmar commented Jan 28, 2019

forgot to mention i'm running this in a cloud function. Meaning the payload would be located in r.body

@CodebyOmar CodebyOmar changed the title Validator always returns error Validating request body always returns error Jan 28, 2019
@CodebyOmar
Copy link
Author

solved. changed p := new(Payload) to var p Payload.

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