github.com/altipla-consulting/ravendb-go-client@v0.1.3/generate_id.go (about) 1 package ravendb 2 3 import ( 4 "reflect" 5 ) 6 7 // tryGetIDFromInstance returns value of ID field on struct if it's of type 8 // string. Returns empty string if there's no ID field or it's not string 9 func tryGetIDFromInstance(entity interface{}) (string, bool) { 10 rv := reflect.ValueOf(entity) 11 for rv.Kind() == reflect.Ptr { 12 rv = rv.Elem() 13 } 14 if rv.Kind() != reflect.Struct { 15 // TODO: maybe panic? 16 return "", false 17 } 18 structType := rv.Type() 19 nFields := rv.NumField() 20 for i := 0; i < nFields; i++ { 21 structField := structType.Field(i) 22 name := structField.Name 23 if name != "ID" { 24 continue 25 } 26 if structField.Type.Kind() != reflect.String { 27 continue 28 } 29 // there is ID field of string type but it's only valid 30 // if not empty string 31 s := rv.Field(i).String() 32 return s, s != "" 33 } 34 return "", false 35 } 36 37 // trySetIDOnEnity tries to set value of ID field on struct to id 38 // returns false if entity has no ID field or if it's not string 39 func trySetIDOnEntity(entity interface{}, id string) bool { 40 rv := reflect.ValueOf(entity) 41 for rv.Kind() == reflect.Ptr { 42 rv = rv.Elem() 43 } 44 if rv.Kind() != reflect.Struct { 45 // TODO: maybe panic? 46 return false 47 } 48 structType := rv.Type() 49 nFields := rv.NumField() 50 for i := 0; i < nFields; i++ { 51 structField := structType.Field(i) 52 name := structField.Name 53 if name != "ID" { 54 continue 55 } 56 if structField.Type.Kind() != reflect.String { 57 continue 58 } 59 field := rv.Field(i) 60 if !field.CanSet() { 61 return false 62 } 63 rv.Field(i).SetString(id) 64 return true 65 } 66 return false 67 }