initial commit before refactor switch
This commit is contained in:
88
server/funcs_r00tclient.go
Normal file
88
server/funcs_r00tclient.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
`reflect`
|
||||
`strings`
|
||||
)
|
||||
|
||||
/*
|
||||
ToMap generates and returns a map representation of a R00tClient.
|
||||
|
||||
Keys by default use the YAML tag for the name.
|
||||
If they are specified with the tag `renderName:"-"`, they are skipped.
|
||||
If they are specified with the tag `renderName:"Foo"`, the string "Foo" will
|
||||
be used as the key instead.
|
||||
Only bools, strings, and pointers thereof are allowed.
|
||||
|
||||
m will never be nil, but may be empty.
|
||||
|
||||
Currently err will always be nil but is specified for future API compatibility.
|
||||
It should be handled by callers for future-proofing, as it may not always be nil
|
||||
in the future.
|
||||
*/
|
||||
func (r *R00tClient) ToMap() (m map[string]string, err error) {
|
||||
|
||||
var ok bool
|
||||
var tagVal string
|
||||
var field reflect.StructField
|
||||
var fieldVal reflect.Value
|
||||
var rootVal reflect.Value
|
||||
|
||||
m = make(map[string]string)
|
||||
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
rootVal = reflect.ValueOf(r).Elem()
|
||||
|
||||
for i := 0; i < rootVal.NumField(); i++ {
|
||||
field = rootVal.Type().Field(i)
|
||||
fieldVal = rootVal.Field(i)
|
||||
|
||||
// Only exported.
|
||||
if field.PkgPath != "" {
|
||||
continue
|
||||
}
|
||||
// Get the key name.
|
||||
tagVal = field.Tag.Get(prettyTag)
|
||||
if tagVal == "-" {
|
||||
continue
|
||||
}
|
||||
if _, ok = field.Tag.Lookup(prettyTag); !ok {
|
||||
tagVal = field.Tag.Get("yaml")
|
||||
if tagVal == "" || strings.HasPrefix(tagVal, "-") {
|
||||
// Use the field name itself. YOLO
|
||||
tagVal = field.Name
|
||||
} else {
|
||||
tagVal = strings.Split(tagVal, ",")[0]
|
||||
}
|
||||
}
|
||||
switch fieldVal.Kind() {
|
||||
case reflect.Bool:
|
||||
if fieldVal.Interface().(bool) {
|
||||
m[tagVal] = trueUaFieldStr
|
||||
} else {
|
||||
m[tagVal] = falseUaFieldStr
|
||||
}
|
||||
case reflect.String:
|
||||
m[tagVal] = fieldVal.String()
|
||||
case reflect.Ptr:
|
||||
if fieldVal.IsNil() {
|
||||
m[tagVal] = nilUaFieldStr
|
||||
} else {
|
||||
switch fieldVal.Type().Elem().Kind() {
|
||||
case reflect.Bool:
|
||||
if fieldVal.Elem().Bool() {
|
||||
m[tagVal] = trueUaFieldStr
|
||||
} else {
|
||||
m[tagVal] = falseUaFieldStr
|
||||
}
|
||||
case reflect.String:
|
||||
m[tagVal] = fieldVal.Elem().String()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
Reference in New Issue
Block a user