【发布时间】: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
-
你不能只用过滤器做你想做的事吗?
-
这是一个名为“函数”的语言特性。