1 개요[ | ]
- Go getValueFromPath()
2 struct[ | ]
Go
Copy
package main
import (
"fmt"
"reflect"
"strings"
)
type User struct {
Name string
Profile Profile
}
type Profile struct {
Email string
Phone string
}
func main() {
user := User{
Name: "John Doe",
Profile: Profile{
Email: "john.doe@example.com",
Phone: "123-456-7890",
},
}
fmt.Println(getValueFromPath(user, "X")) // <nil>
fmt.Println(getValueFromPath(user, "Name")) // "John Doe"
fmt.Println(getValueFromPath(user, "Profile")) // {john.doe@example.com 123-456-7890}
fmt.Println(getValueFromPath(user, "Profile.Email")) // "john.doe@example.com"
fmt.Println(getValueFromPath(user, "Profile.Phone")) // "123-456-7890"
}
func getValueFromPath(v interface{}, path string) interface{} {
fields := strings.Split(path, ".")
rv := reflect.ValueOf(v)
for _, field := range fields {
rv = rv.FieldByName(field)
if !rv.IsValid() {
return nil
}
}
return rv.Interface()
}
3 json[ | ]
Go
Copy
package main
import (
"fmt"
"reflect"
"strings"
)
type User struct {
Name string `json:"name"`
Profile Profile `json:"profile"`
}
type Profile struct {
Email string `json:"email"`
Phone string `json:"phone"`
}
func main() {
user := User{
Name: "John Doe",
Profile: Profile{
Email: "john.doe@example.com",
Phone: "123-456-7890",
},
}
fmt.Println(getValueFromPath(user, "x")) // <nil>
fmt.Println(getValueFromPath(user, "name")) // "John Doe"
fmt.Println(getValueFromPath(user, "profile")) // {john.doe@example.com 123-456-7890}
fmt.Println(getValueFromPath(user, "profile.email")) // "john.doe@example.com"
fmt.Println(getValueFromPath(user, "profile.phone")) // "123-456-7890"
}
func getValueFromPath(v interface{}, path string) interface{} {
fields := strings.Split(path, ".")
rv := reflect.ValueOf(v)
for _, field := range fields {
rv = reflect.Indirect(rv)
switch rv.Kind() {
case reflect.Struct:
rv = rv.FieldByNameFunc(func(name string) bool {
fieldType, _ := rv.Type().FieldByName(name)
jsonTag := fieldType.Tag.Get("json")
return jsonTag == field || strings.EqualFold(name, field)
})
default:
return nil
}
if !rv.IsValid() {
return nil
}
}
return rv.Interface()
}
4 같이 보기[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.