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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line