我的意圖是在兩個響應結構的頭部和主體中使用HTTP狀態碼。如果沒有設置狀態碼兩次作爲函數參數,並且再次爲結構設置以避免冗餘。如何訪問接口的屬性
參數response
的JSON()
是一個接口,允許兩個結構被接受。編譯器會拋出以下異常:
response.Status undefined (type interface {} has no field or method Status)
因爲響應字段不能有狀態屬性。有沒有其他方法來避免設置狀態碼兩次?
type Response struct {
Status int `json:"status"`
Data interface{} `json:"data"`
}
type ErrorResponse struct {
Status int `json:"status"`
Errors []string `json:"errors"`
}
func JSON(rw http.ResponseWriter, response interface{}) {
payload, _ := json.MarshalIndent(response, "", " ")
rw.WriteHeader(response.Status)
...
}
感謝您的解決方案。現在是否更好,因此將狀態代碼設置爲新參數兩次並在結構中設置兩次,或者編寫兩個新函數和一個實現相同的接口? – user3147268
nit:'DataResponse'可能比'OKResponse'好。 'Status()int'接口的另一個名字是'Statuser'或者'Status'(前者聽起來不正確,但是這樣的''er'非字接口有優先權。 –
Thanks @ Dave-C。稍微改變了答案。 –