小编Jag*_*ata的帖子

http在golang中覆盖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: …
Run Code Online (Sandbox Code Playgroud)

error-handling http go net-http

3
推荐指数
1
解决办法
3582
查看次数

标签 统计

error-handling ×1

go ×1

http ×1

net-http ×1