Cannot read StructTag for some reason

66 views Asked by At

I have this handler:

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)
    })
}

the tc.ExtractType func looks like:

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)
    }
}

it's able to find the "type" tag, which points to "star", but for some reason it's not picking up the "tc_resp_body_type" tag which points to "true". Here is what I get logged out:

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

does anyone know why the "type" tag can be found, but the "tc_req_body_type" cannot be found?

2

There are 2 answers

0
AudioBubble On BEST ANSWER

ughh I think it needs to be:

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

using a comma like this is not correct?

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

can someone confirm?

0
ssemilla On

reflect.StructTag Get() and LookUp() parses using a tag convention defined in 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.

So just change your tags like this:

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