Golang中的HTTP覆盖HTTP标头代码,而JSON编码出现错误



考虑此情况!

成功执行HTTP请求后,如果执行JSON编码时出现错误,如何覆盖标题代码

func writeResp(w http.ResponseWriter, code int, data interface{}) {
    w.Header().Set("Content-Type", "application/json")
    //Here I set the status to 201 StatusCreated
    w.WriteHeader(code) 
    s := success{Data: data}
    //what if there is an error here and want to override the status to 5xx error
    //how to handle error here, panic?, http.Error() is not an option because as we already wrote header to 201, it just prints `http: multiple response.WriteHeader calls`
    if err := json.NewEncoder(w).Encode(s); err != nil {
        w.Header().Set("Content-Type", "application/json")
        //it throws http: multiple response.WriteHeader calls here as we already wrote header above to 201
        w.WriteHeader(code)
        e := errorResponse{
            Code:        code,
            Error:       error,
            Description: msg,
        }
        if err := json.NewEncoder(w).Encode(e); err != nil {
         //same how to handle here
        }
    }
}

我在这里有多个选项,如果我们只是致命登录用户,即使我使用w.Write([]byte(msg))编写字符串仍然不知道发生了什么,仍然状态是201创建的,如何使用错误代码响应错误代码5xx

任何帮助都非常感谢

首先,编码时似乎不太可能遇到错误。

出于Marshal失败的原因,请参见此问题:

什么输入会导致Golang的Json.marshal返回错误?

其他潜在的错误原因将是将数据实际写入响应流的一些问题,但是在这种情况下,您也无法编写自定义错误。

回到您的问题,如果您担心编码对象可能会失败,则可以首先使用数据(检查错误检查(,然后仅编写201个状态代码(和编码数据(,如果架设成功。<<<<<<<<

修改您的示例:

s := success{Data: data}
jsonData, err := json.Marshal(s)
if err != nil {
    // write your error to w, then return
}
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)

现在,最后一个write也可能会丢失错误。

但是,如果发生这种情况,它在编写自定义错误时也会失败,因此,在这种情况下,您最好在服务器端登录(或将该错误发送给New Relic等跟踪器等(。

最新更新