考虑以下代码,该代码响应 GET '/venues/:id' 请求:
我的structToJSON函数以空接口作为参数,因为我想将各种不同的结构体传递给该函数,并将它们输出为JSON。但是,这似乎并不是很安全。如果任何东西都能满足空接口,我可以将任何我想要的东西传递到该函数中,当json.Marshal尝试执行其操作时就会发生各种错误。这(我想)会被编译器捕获而非在运行时捕获,但是否有更安全的方法呢?我可以为每种不同类型的Struct/Model复制structToJSON方法,但这不太符合DRY原则。谢谢。
func venueShow(w http.ResponseWriter, req *http.Request) {
// get ID from params
vars := mux.Vars(req)
id := vars["id"]
// initialise new struct
var venue Venue
// select by id and scan into struct
db.First(&venue, id).Scan(&venue)
// turn it to json
response := structToJSON(&venue)
// write headers and provide response
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
并且:
func structToJSON (s interface{}) (response []byte) {
// turn it into pretty-ish json
response, err := json.MarshalIndent(&s, "", " ")
if err != nil {
return []byte("Venue does not exist")
}
// return the json as the reponse
return response
}
我的structToJSON函数以空接口作为参数,因为我想将各种不同的结构体传递给该函数,并将它们输出为JSON。但是,这似乎并不是很安全。如果任何东西都能满足空接口,我可以将任何我想要的东西传递到该函数中,当json.Marshal尝试执行其操作时就会发生各种错误。这(我想)会被编译器捕获而非在运行时捕获,但是否有更安全的方法呢?我可以为每种不同类型的Struct/Model复制structToJSON方法,但这不太符合DRY原则。谢谢。