Created
February 27, 2020 11:57
-
-
Save ibraabada/4f332c1654a1769e5b45d597ed0f06e4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"github.com/go-playground/validator/v10" | |
) | |
func UnmarshalFoo(data []byte) (Foo, error) { | |
var r Foo | |
err := json.Unmarshal(data, &r) | |
return r, err | |
} | |
func (r *Foo) MarshalFoo() ([]byte, error) { | |
return json.Marshal(r) | |
} | |
type Foo struct { | |
Property1 string `json:"prop1" validate:"ne=BABA,required"` | |
Property2 string `json:"prop2" validate:"required"` | |
} | |
var validate *validator.Validate | |
func main() { | |
fmt.Println("BEGIN") | |
validate = validator.New() | |
invalidInput:= "{\"prop1\":\"BABA\",\"prop2\":\"value2\"}" | |
validInput := "{\"prop1\":\"value1\",\"prop2\":\"value2\"}" | |
invalidInputBytes := []byte(invalidInput) | |
validInputBytes := []byte(validInput) | |
validObject, err := UnmarshalFoo(validInputBytes) | |
if err != nil { | |
fmt.Printf("ERROR UNMARSHAL: %s\n\n", err) | |
} | |
fmt.Printf("UNMARSHALED RESULT invalid input: %s\n\n", validObject) | |
invalidObject, err := UnmarshalFoo(invalidInputBytes) | |
if err != nil { | |
fmt.Printf("ERROR UNMARSHAL: %s\n\n", err) | |
} | |
fmt.Printf("UNMARSHALED RESULT valid input: %s\n\n", invalidObject) | |
errs := validate.Struct(invalidObject) | |
if errs!= nil { | |
for k, v := range errs.(validator.ValidationErrors) { | |
// Create error messages based on errors returned ... | |
fmt.Println(k, v) | |
} | |
}else { | |
fmt.Println("VALID INPUT") | |
} | |
errs = validate.Struct(validObject) | |
if err != nil { | |
for k, v := range errs.(validator.ValidationErrors) { | |
// Create error messages based on errors returned ... | |
fmt.Println(k, v) | |
} | |
}else { | |
fmt.Println("VALID INPUT") | |
} | |
fmt.Printf("END") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment