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)
            }
        },
      )
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题