Guest User

Untitled

a guest
Dec 16th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  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. }
Add Comment
Please, Sign In to add comment