0
这里是我需要做的,并不能找到我需要为了做到这一点的资源:golang解组结构函数,它不知道的类型,并依靠接口
我需要编写一个通用函数将为MOCK服务器设置处理程序。这个处理程序将接收一个JSON对象,并且必须取消它并将其与参考结构进行比较,并根据两个对象之间的对应关系来相应地设置其状态。 这里有个诀窍:我们不知道函数内部是什么类型的引用。
< =====我现在在哪里====> 我写了这个函数,不起作用。
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)
}
},
)
}
这里是我如何使用它:
ref := MyStruct{...NotEmpty...}
received := MyStruct{}
createHandlerToTestDelete("aRoute", ref, received)
结果是服务器时做解组不会在意原始类型接收可变的。
有人有想法吗?
非常感谢,好像我应该去看看反射和json的内容更好看! – MrBouh