doutangxi2144 2017-01-18 10:39
浏览 134
已采纳

如何在Go中实例化未知类型的值?

I develop some server in golang. I try to create some wrapper-function, which can helps me in future.

What I have:

1) I had some DTO structs, for example:

type Request struct {
    Field1   string `json:"field1"`
    Field2   string `json:"field2"`
}

type Response struct {
    Field1   string `json:"field1"`
    Field2   string `json:"field2"`
    Field3   string `json:"field3"`
}

2) I had some functions, in controller layer, which (by conventions) receives 1 argument (pointer to struct) and returns 1 result (pointer to struct), for example:

func SomeHandler(request *Request) *Response{
    ...do something
    return &Response{"first","second","third"}
}

What I need:

I need to write wrapper function which receives as argument:

  1. pointer to 'controller' function
  2. http.ResponseWriter
  3. *http.Request

This wrapper function must:

  1. Determine type of argument of 'controller' function
  2. Determine type of result of 'controller' function
  3. Instantiate and fill argument value from Body of *http.Request (decode from json)
  4. Call controller Function with instantiated on previous step argument
  5. Write results of previous step into http.ResponseWriter (encoded as json)

Wrapper must work correct with any types of 'controller' functions - signatures of this functions is different (different argument type, different result type)

Can anybody help me with implementing of this wrapper?

展开全部

  • 写回答

2条回答 默认 最新

  • donglian6625 2017-01-18 10:55
    关注

    What you're doing is a bit weird but reflect can provide all the info you need.

    func myFunction(a string, b int32) error {
        return nil
    }
    
    func myWrapper(mystery interface{}) {
        typ := reflect.TypeOf(mystery)
    
        // Check typ.Kind before playing with In(i);
        for i := 0; i < typ.NumIn(); i++ {
            fmt.Printf("Param %d: %v
    ", i, typ.In(i))
        }
        for i := 0; i < typ.NumOut(); i++ {
            fmt.Printf("Result %d: %v
    ", i, typ.Out(i))
        }
    
    }
    

    This prints:

    Param 0: string
    Param 1: int32
    Result 0: error
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部