【问题标题】:Golang set http response code based on struct fieldGolang根据struct字段设置http响应码
【发布时间】:2015-05-01 19:04:06
【问题描述】:

在我正在编写的 api 中,我有一个编组为 json 的错误结构。当 api 出现错误时,它返回结构,我将 http 响应代码设置为适当的值。

type PodsError struct {
    ErrorCode       int     `json:"error_code"`
    CallingFunction string  `json:"calling_function"`
    Message         string  `json:"error_message"`
}

type PodsErrorWrapper struct {
    Error   PodsError   `json:"error"`
}

现在每次我写结构体时我也会写一个标题,但我不喜欢我看到的重复代码的数量。

error := PodsError{http.StatusNotFound, "Calling Func", "Message"}
response.WriteHeader(error.ErrorCode)
response.WriteEntity(PodsErrorWrapper{error})

是否可以将 WriteHeader 调用移动到每当我将错误传递给 WriteEntity() 时都会调用的东西?我认为必须有一个我可以为 PodsErrorWapper 实现的函数,我可以将 http 状态设置为 ErrorCode 字段的任何值。

编辑:抱歉我忘了提,我使用的是 go-restful 包 (github.com/emicklei/go-restful)

【问题讨论】:

  • 你使用什么包?我不知道提供了什么WriteEntity
  • 哎呀抱歉我忘了提,我正在使用 github.com/emicklei/go-restful
  • 你不能只用过滤器做你想做的事吗?
  • 这是一个名为“函数”的语言特性。

标签: http struct go


【解决方案1】:

您可以制作自己的功能:

func writeEntity(r *restful.Response, value interface{}) error {
    // if value is an error
    if perr, ok := value.(PodsError); ok {
        r.WriteHeader(perr.ErrorCode)
        // reassign value so it gets wrapped: `{"error": value}`
        value = struct {
            Error PodsError `json:"error"`
        }{perr}
    }
    return r.WriteEntity(value)
}

然后总是调用它而不是response.WriteEntity

writeEntity(response, PodsError{http.StatusNotFound, "Calling Func", "Message"})

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 2019-09-19
    • 2018-12-25
    • 2022-12-29
    • 2020-10-01
    相关资源
    最近更新 更多