-
Notifications
You must be signed in to change notification settings - Fork 0
/
hxtag.go
102 lines (88 loc) · 2.27 KB
/
hxtag.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package httpx
import (
"reflect"
"strings"
"github.com/madlabx/pkgx/errors"
"github.com/madlabx/pkgx/log"
)
var (
tagHttpX = "hx_tag"
tagHttpXFieldPlace = "hx_place"
tagHttpXFieldName = "hx_name"
tagHttpXFieldMust = "hx_must"
tagHttpXFieldDefault = "hx_default"
tagHttpXFieldRange = "hx_range"
)
const (
constHxPlaceBody = "body"
constHxPlaceQuery = "query"
constHxPlaceHeader = "header"
constHxPlaceEither = ""
)
type hxTag struct {
place string
name string
must bool
defaultValue string
valueRange string
}
func (ht *hxTag) realName(name string) string {
if ht.name == "" {
return name
} else {
return ht.name
}
}
func (ht *hxTag) inQuery() bool {
return ht.place == constHxPlaceQuery || ht.place == constHxPlaceEither
}
func (ht *hxTag) inBody() bool {
return ht.place == constHxPlaceBody || ht.place == constHxPlaceEither
}
func (ht *hxTag) inHeader() bool {
return ht.place == constHxPlaceHeader
}
func (ht *hxTag) isEmpty() bool {
return ht.name == "" &&
!ht.must &&
ht.defaultValue == "" &&
ht.valueRange == ""
}
func parseHxTag(t reflect.StructTag, paths ...string) (*hxTag, error) {
var (
place, name, mustStr, defaultValue, valueRange string
must bool
)
tags := t.Get(tagHttpX)
if len(tags) > 0 {
tagList := strings.Split(tags, ";")
if len(tagList) != 5 {
return nil, errors.Errorf("invalid "+tagHttpX+":'%v' which should have 5 fields, path:%v", tags, paths)
}
place, name, mustStr, defaultValue, valueRange = tagList[0], tagList[1], tagList[2], tagList[3], tagList[4]
} else {
place, name, mustStr, defaultValue, valueRange =
t.Get(tagHttpXFieldPlace),
t.Get(tagHttpXFieldName),
t.Get(tagHttpXFieldMust),
t.Get(tagHttpXFieldDefault),
t.Get(tagHttpXFieldRange)
}
if strings.ToLower(mustStr) == "true" {
must = true
} else if strings.ToLower(mustStr) == "false" {
must = false
} else if len(mustStr) > 0 {
return nil, errors.Errorf("invalid must tag:%v", mustStr)
}
if must && len(defaultValue) > 0 {
log.Warn("should not define both of hx_must and hx_defaultValue")
}
return &hxTag{
place: place,
name: name,
must: must,
defaultValue: defaultValue,
valueRange: valueRange,
}, nil
}