daily pastebin goal
56%
SHARE
TWEET

Untitled

a guest Dec 16th, 2018 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2. import (
  3.   "reflect"
  4. )
  5.  
  6. // If you can verify fields without reflection, you should not use this!
  7.  
  8. // This can be useful when verifying JSON input from clients
  9.  
  10. // Pass in reference to object
  11. // obj: struct to verify fields (pass reference with &)
  12. // omitFields: map of field name to whether or not they should be omitted from the search
  13. // fillEmpty: whether or not to fill empty fields with their zero value
  14. // Returns whether or not all the fields (excluding omitFields) are non-nil
  15.  
  16. func VerifyFieldsExist(obj interface{}, omitFields map[string]bool, fillEmpty bool) bool {
  17.     v := reflect.ValueOf(obj).Elem()
  18.     for i := 0; i < v.NumField(); i++ {
  19.         if v.Field(i).IsNil() {
  20.             if !omitFields[v.Type().Field(i).Name] {
  21.                 return false
  22.             } else if fillEmpty {
  23.                 v.Field(i).Set(reflect.New(v.Field(i).Type().Elem())) // zero the value if needed to fill empty
  24.             }
  25.         }
  26.     }
  27.     return true
  28. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top