【发布时间】:2015-05-20 17:32:45
【问题描述】:
我打算在两个响应结构的标头和正文中都使用 HTTP 状态代码。但是,没有将状态码设置为函数参数两次,并再次为结构体设置以避免冗余。
JSON() 的参数response 是一个允许两个结构都被接受的接口。编译器抛出以下异常:
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)
...
}
【问题讨论】: