doulian8485 2015-05-01 19:04
浏览 45

Golang根据结构字段设置http响应代码

Within an api I'm writing I have an error struct which marshals to json. When the api has an error it returns the struct and I set the http response code to be the appropriate value.

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"`
}

Right now every time I write the struct I also write a header, but I don't like the amount of duplicate code I am seeing.

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

Is it possible to move the WriteHeader call to something that gets called whenever I pass the error to WriteEntity()? I figure there has to be a function I could implement for a PodsErrorWapper where I could just set the http status to be whatever the ErrorCode field is.

Edit: Sorry I forgot to mention, I am using the go-restful package (github.com/emicklei/go-restful)

  • 写回答

1条回答 默认 最新

  • dongsetan3216 2015-05-01 22:29
    关注

    You can make your own function:

    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)
    }
    

    Then just always call that instead of response.WriteEntity:

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

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算