dragon7088 2017-03-08 16:56
浏览 47
已采纳

不知道类型并依赖接口的golang Unmarshal Struct In Function

here is what I need to do and can't find the resource I need in order to do it:

I need to write a generic function that will setup a handler for a MOCK server. This handler will receive a JSON object and have to unMarshall it and compare it to a reference structure and set its status accordingly depending on the correspondence between both object. Here is the trick: we do not know inside the function what is the type of the reference.

<===== Where am I at this point ====> I wrote this function, which doesn't work.

func createHandlerToTestDelete(route string, ref interface{}, received interface{}){
    Servmux.HandleFunc(route,
        func(w http.ResponseWriter, r *http.Request) {
            // recreate a structure from body content
            body, _ := ioutil.ReadAll(r.Body)
            json.Unmarshal(body, &received)

            // comparison between ref and received
            if reflect.DeepEqual(received, ref) {
                w.WriteHeader(http.StatusOK)
            } else {
                w.WriteHeader(http.StatusInternalServerError)
            }
        },
    )
}

here is how I am using it:

ref := MyStruct{...NotEmpty...}
received := MyStruct{}
createHandlerToTestDelete("aRoute", ref, received)

The result is that the server when doing Unmarshal will not care of the original type of the received variable.

Does someone has an idea?

  • 写回答

1条回答 默认 最新

  • dongmu1914 2017-03-08 17:03
    关注

    Use reflect.New to create a pointer to a value with the same type as the reference type.

    func createHandlerToTestDelete(route string, ref interface{}) {
      t := reflect.TypeOf(ref)
      ServeMux.HandleFunc(route,
        func(w http.ResponseWriter, r *http.Request) {
            v := reflect.New(t)
            if err := json.NewDecoder(r.Body).Decode(v.Interface()); err != nil {
                // handle error
            }
            // v is pointer to value. Get element for correct comparison.
            if reflect.DeepEqual(v.Elem().Interface(), ref) {
                w.WriteHeader(http.StatusOK)
            } else {
                w.WriteHeader(http.StatusInternalServerError)
            }
        },
      )
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器