interface - 如何访问接口(interface)的属性

标签 interface go

我打算在两个响应结构的 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/

相关文章:

安卓BetterPickers

java - 接口(interface)和节点的存储和使用

javascript - 如何在我的 React 类中的接口(interface)中包含接口(interface)?

go - 复制有条件的目录

go - 访问多对多表数据

C#调用接口(interface)方法非虚实现

java - 如何提供不同插件采用不同参数的插件模型

Golang : Interrupting infinite polling having time. 休眠

string - 在Go中逐行读取文件

go - golang中括号和花括号的区别