tags.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package ndr
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. )
  7. const ndrNameSpace = "ndr"
  8. type tags struct {
  9. Values []string
  10. Map map[string]string
  11. }
  12. // parse the struct field tags and extract the ndr related ones.
  13. // format of tag ndr:"value,key:value1,value2"
  14. func parseTags(st reflect.StructTag) tags {
  15. s := st.Get(ndrNameSpace)
  16. t := tags{
  17. Values: []string{},
  18. Map: make(map[string]string),
  19. }
  20. if s != "" {
  21. ndrTags := strings.Trim(s, `"`)
  22. for _, tag := range strings.Split(ndrTags, ",") {
  23. if strings.Contains(tag, ":") {
  24. m := strings.SplitN(tag, ":", 2)
  25. t.Map[m[0]] = m[1]
  26. } else {
  27. t.Values = append(t.Values, tag)
  28. }
  29. }
  30. }
  31. return t
  32. }
  33. func appendTag(t reflect.StructTag, s string) reflect.StructTag {
  34. ts := t.Get(ndrNameSpace)
  35. ts = fmt.Sprintf(`%s"%s,%s"`, ndrNameSpace, ts, s)
  36. return reflect.StructTag(ts)
  37. }
  38. func (t *tags) StructTag() reflect.StructTag {
  39. mv := t.Values
  40. for key, val := range t.Map {
  41. mv = append(mv, key+":"+val)
  42. }
  43. s := ndrNameSpace + ":" + `"` + strings.Join(mv, ",") + `"`
  44. return reflect.StructTag(s)
  45. }
  46. func (t *tags) delete(s string) {
  47. for i, x := range t.Values {
  48. if x == s {
  49. t.Values = append(t.Values[:i], t.Values[i+1:]...)
  50. }
  51. }
  52. delete(t.Map, s)
  53. }
  54. func (t *tags) HasValue(s string) bool {
  55. for _, v := range t.Values {
  56. if v == s {
  57. return true
  58. }
  59. }
  60. return false
  61. }