dqlxtv1452 2019-05-14 13:31
浏览 646
已采纳

在HTTP响应中对分块数据如何设置Content-Length

We have written a service which sends some encoded data as chunked to a proxy service which need Content-Length header to be set so that it can send proper response to end point. Even if I set the Content-Length header still it get stripped as part of the response to the client. Below is the code which set the header

func HTTPSuccessResponse(rw http.ResponseWriter, bufferLen int, media []byte) {
        rw.WriteHeader(http.StatusOK)

        rw.Header().Set("Content-Type", "opus/ogg; audio/ogg; codec=opus")
        length := strconv.Itoa(len(media));
        rw.Header().Set("Content-Length", length)
        rw.Write(media)
}

Below is the response I get when I try to the request using curl

bash-4.2# curl -v -X GET -k -H  -i 'http://127.0.0.1:8090/preview'
* About to connect() to 127.0.0.1 port 8090 (#0)
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 8090 (#0)
> GET /preview HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 127.0.0.1:8090
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 14 May 2019 13:08:20 GMT
< Content-Type: text/plain; charset=utf-8
< Transfer-Encoding: chunked
<

I am using Gorrila Mux library for setting up HTTP server. Any thoughts how to make the header as part of the response.

  • 写回答

1条回答 默认 最新

  • dpl3350 2019-05-14 13:38
    关注

    Remove the WriteHeader call at the top. You can only write headers to a response once. After you call WriteHeader you can't set any more headers.

    Per the ResponseWriter documentation:

        // Changing the header map after a call to WriteHeader (or
        // Write) has no effect unless the modified headers are
        // trailers.
    

    So you can't call it first; but you also don't need to call it at all - from the same docs:

        // If WriteHeader is not called explicitly, the first call to Write
        // will trigger an implicit WriteHeader(http.StatusOK).
        // Thus explicit calls to WriteHeader are mainly used to
        // send error codes.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵