Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "reflect"
- )
- // If you can verify fields without reflection, you should not use this!
- // This can be useful when verifying JSON input from clients
- // Pass in reference to object
- // obj: struct to verify fields (pass reference with &)
- // omitFields: map of field name to whether or not they should be omitted from the search
- // fillEmpty: whether or not to fill empty fields with their zero value
- // Returns whether or not all the fields (excluding omitFields) are non-nil
- func VerifyFieldsExist(obj interface{}, omitFields map[string]bool, fillEmpty bool) bool {
- v := reflect.ValueOf(obj).Elem()
- for i := 0; i < v.NumField(); i++ {
- if v.Field(i).IsNil() {
- if !omitFields[v.Type().Field(i).Name] {
- return false
- } else if fillEmpty {
- v.Field(i).Set(reflect.New(v.Field(i).Type().Elem())) // zero the value if needed to fill empty
- }
- }
- }
- return true
- }
Add Comment
Please, Sign In to add comment