2017-03-08 60 views
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) 

结果是服务器时做解组不会在意原始类型接收可变的。

有人有想法吗?

回答

1

使用reflect.New创建一个指向与引用类型具有相同类型的值的指针。

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) 
     } 
    }, 
) 
} 
+0

非常感谢,好像我应该去看看反射和json的内容更好看! – MrBouh