Advertisement
Guest User

Untitled

a guest
Oct 28th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "reflect"
  6. )
  7.  
  8. // PrintTags prints all tag values for the given struct.
  9. func PrintTags(s interface{}, tag string) {
  10. st := reflect.TypeOf(s)
  11.  
  12. for i := 0; i < st.NumField(); i++ {
  13. f := st.Field(i)
  14. fmt.Printf("field=%s\t%s=%s\n", f.Name, tag, f.Tag.Get(tag))
  15. }
  16. }
  17.  
  18. // Populate sets values of the input struct by using a struct tag as a key
  19. // into a values map.
  20. func Populate(s interface{}, tag string, values map[string]string) {
  21. st := reflect.TypeOf(s).Elem()
  22. v := reflect.ValueOf(s).Elem()
  23.  
  24. for i := 0; i < st.NumField(); i++ {
  25. f := st.Field(i)
  26. key := f.Tag.Get(tag)
  27. value := values[key]
  28. v.Field(i).SetString(value)
  29. }
  30. }
  31.  
  32. type Example struct {
  33. A string `namespace:"hello"`
  34. B string `namespace:"world"`
  35. }
  36.  
  37. func main() {
  38. e := Example{}
  39.  
  40. PrintTags(e, "namespace")
  41.  
  42. values := map[string]string{
  43. "hello": "a",
  44. "world": "b",
  45. }
  46. fmt.Println(e)
  47. Populate(&e, "namespace", values)
  48. fmt.Println(e)
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement