doutangxi2144 2017-01-18 18: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 18: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条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?