由于某种原因,无法读取StructTag



我有这个处理程序:

func (h Handler) makeGetMany(v PeopleInjection) http.HandlerFunc {
type RespBody struct {
TypeCreatorMeta string `type:"bar",tc_resp_body_type:"true"`
}
type ReqBody struct {
TypeCreatorMeta string `type:"star",tc_req_body_type:"true"`
Handle string
}
return tc.ExtractType(
tc.TypeList{ReqBody{},RespBody{}},
func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(v.People)
})
}

tc.ExtractType函数看起来像:

type TypeList = []interface{}
func ExtractType(s TypeList, h http.HandlerFunc) http.HandlerFunc {
m := make(map[string]string)
for _, v := range s {
t := reflect.TypeOf(v)
f, _ := t.FieldByName("TypeCreatorMeta")
fmt.Println("All tags?:",f.Tag);
v, ok := f.Tag.Lookup("type")
if !ok {
fmt.Println("no 'type' tag.");
continue;
}
for _, key := range []string{"tc_req_body_type", "tc_resp_body_type"} {
_, ok := f.Tag.Lookup(key)
fmt.Println(ok,"key:",key)   // <<<< important
if ok {
m[key] = v
}
}
}
return func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("Req: %sn", r.URL.Path)
h.ServeHTTP(w, r)
}
}

它能够找到指向"star"的"type"标记,但由于某种原因,它没有找到指向"true"的"tcpsp_body_type"标记。以下是我注销的内容:

All tags?: type:"star",tc_req_body_type:"true"
false key: tc_req_body_type
false key: tc_resp_body_type

有人知道为什么可以找到"type"标记,却找不到"tc_reqbody_type"吗?

reflect.StructTagGet()LookUp()使用反射中定义的标记约定进行解析。结构标签

按照惯例,标记字符串是可选的空格分隔键:"值"对的串联。每个键都是一个非空字符串,由空格(U+0020"(、引号(U+0022"(和冒号(U+003A':'(以外的非控制字符组成。每个值都使用U+0022'"字符和Go字符串文本语法进行引用。

所以只需像这样更改您的标签:

type RespBody struct {
TypeCreatorMeta string `type:"bar" tc_resp_body_type:"true"`
}

ughh我认为它需要:

TypeCreatorMeta string `type:"bar" tc_resp_body_type:"true"` // no comma

用这样的逗号不正确吗?

TypeCreatorMeta string `type:"bar",tc_resp_body_type:"true"`

有人能确认吗?

最新更新