我打算在两个响应结构的 header 和正文中都使用 HTTP 状态代码。 Bu 没有将状态代码设置为函数参数两次,并且再次为结构避免冗余。
JSON()
的参数response
是一个允许两种结构都被接受的接口(interface)。编译器抛出以下异常:
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)
...
}
最佳答案
rw.WriteHeader(response.Status)
中的response
类型是interface{}
。在 Go 中,您需要显式断言底层结构的类型,然后访问该字段:
func JSON(rw http.ResponseWriter, response interface{}) {
payload, _ := json.MarshalIndent(response, "", " ")
switch r := response.(type) {
case ErrorResponse:
rw.WriteHeader(r.Status)
case Response:
rw.WriteHeader(r.Status)
}
...
}
然而,更好的首选方法是为您的响应定义一个通用接口(interface),该接口(interface)具有获取响应状态的方法:
type Statuser interface {
Status() int
}
// You need to rename the fields to avoid name collision.
func (r Response) Status() int { return r.ResStatus }
func (r ErrorResponse) Status() int { return r.ResStatus }
func JSON(rw http.ResponseWriter, response Statuser) {
payload, _ := json.MarshalIndent(response, "", " ")
rw.WriteHeader(response.Status())
...
}
最好将 Response
重命名为 DataResponse
并将 ResponseInterface
重命名为 Response
,IMO。
关于interface - 如何访问接口(interface)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30356592/