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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line