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