考慮以下代碼,它響應(yīng) GET '/venues/:id':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 函數(shù)將一個空接口作為參數(shù),因?yàn)槲蚁雽⒏鞣N不同的結(jié)構(gòu)傳遞給該函數(shù)并將它們作為 JSON 輸出。然而,它并沒有讓我覺得很安全。如果有任何東西滿足一個空接口,我可以將任何我想要的東西傳遞給那個函數(shù),當(dāng) json.Marshal 嘗試做它的事情時,可能會發(fā)生各種錯誤。這(我想)會被編譯器捕獲而不是在運(yùn)行時捕獲,但是有沒有更安全的方法?我可以為傳遞給它的每種不同類型的結(jié)構(gòu)/模型復(fù)制 structToJSON 方法,但這不是很 DRY。
1 回答

有只小跳蛙
TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個贊
Marshal 函數(shù)也接收其參數(shù),interface{}因此無法檢測您是否在編譯時傳遞了無效的內(nèi)容,所有這些都在運(yùn)行時被捕獲。
要檢查是否將無效類型傳遞給 Marshal,您可以做的一件事是檢查錯誤類型,UnsupportedTypeError當(dāng)您嘗試編組無效類型(如chan或func)時,Marshal 會返回 ,以便您可以在編組時檢查該錯誤。
所以你可以嘗試這樣的事情:
if err != nil {
_, ok := err.(*json.UnsupportedTypeError)
if ok {
return []byte("Tried to Marshal Invalid Type")
} else {
return []byte("Venue does not exist")
}
}
- 1 回答
- 0 關(guān)注
- 177 瀏覽
添加回答
舉報(bào)
0/150
提交
取消