donglaohua1671 2018-10-17 07:25
浏览 69
已采纳

如何在Go HTTP服务器中有条件地设置HTTP状态代码?

I have the following HTTP handler function:

func (h *UptimeHttpHandler) CreateSchedule(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    dec := json.NewDecoder(r.Body)

    var req ScheduleRequest
    if err := dec.Decode(&req); err != nil {
        // error handling omited
    }

    result, err := saveToDb(req)
    if err != nil {
        // error handling omited
    }

    // Responding with 201-Created instead of default 200-Ok
    w.WriteHeader(http.StatusCreated)

    enc := json.NewEncoder(w)
    if err := enc.Encode(result); err != nil {
        // this will have no effect as the status is already set before
        w.WriteHeader(http.StatusInternalServerError)
        fmt.Fprintf(w, "%v", err)
    }
}

Above code does the following:

  1. Request comes as a JSON data. It is decoded into req
  2. Request is persisted in the DB. This returns a result object which will be the response

Now here, as soon as the DB insert is successful, we set the status code to 201. Then use a JSON encoder to stream the JSON encoded value directly to ResponseWriter.

When encode returns an error, I need to change the status code to 500. But currently I can't do it as Go allows to set the status code only once.

I can handle this by keeping the encoded JSON in memory, and setting the status code only when it is success. But then this creates unwanted copies and not really nice.

Is there a better way to handle this?

  • 写回答

2条回答 默认 最新

  • doutangtan6386 2018-10-17 12:18
    关注

    Expanding my comment a bit:

    There is no way to do this without buffering. And if you think about it, even if there was, how would that be implemented? The response header needs to be sent before the contents. If the code depends on encoding the response, you must first encode, check the result, set the header and flush the encoded buffer.

    So even if the Go API supported a "delayed" status, you would be basically pushing the buffering problem one level down, to the http library :)

    You should make the call - either it's important to get the response code right at all costs and you can afford to buffer, or you want to stream the response and you cannot change the result.

    Theoretically Go could create an encoding validator that will make sure the object you are trying to encode will 100% pass before actually encoding.

    BTW, this makes me think of another thing - the semantic meaning of the response code. You return HTTP Created, right? It's the correct code since the object has in fact been created. But if you return a 500 error due to encoding, has the object not been created? It still has! So the Created code is still valid, the error is just in the encoding stage. So maybe a better design would be not to return the object as a response?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行