gpt4 book ai didi

go - 由于某种原因无法读取 StructTag

转载 作者:IT王子 更新时间:2023-10-29 02:08:13 25 4
gpt4 key购买 nike

我有这个处理程序:

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: %s\n", r.URL.Path)
h.ServeHTTP(w, r)
}
}

它能够找到指向“star”的“type”标签,但由于某种原因它没有找到指向“true”的“tc_resp_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_req_body_type”?

最佳答案

reflect.StructTag Get()LookUp() 使用 reflect.StructTag 中定义的标记约定进行解析

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

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

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

关于go - 由于某种原因无法读取 StructTag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53577297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com