dongqiya9552 2016-06-15 04:14
浏览 48
已采纳

设置静态标头,避免分配?

I am trying to write a Go http handler which is performance sensitive (in particular I want to minimize the amount of RAM used). The handler sets a bunch of headers for each request. All headers are always the same and with the same values. Is there a way to use a single const for all headers and set them all in a single call?

Example. Instead of doing this for all requests:

w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")

…do something like this:

const staticHeaders = `

Access-Control-Allow-Origin: *
Cache-Control: no-cache
Connection: keep-alive`

w.Headers.WriteRaw(staticHeaders)

Is that possible?

  • 写回答

1条回答 默认 最新

  • dongwei2882 2016-06-15 04:51
    关注

    You could hijack the connection, and write the headers directly, but that's only going to save you half the header allocations since the incoming request is still going to allocate a map and strings to fill in the Request struct. It also means that you would need to handle the raw TCP connection yourself from that point forward.

    You should profile thoroughly to ensure that the header allocations are actually a bottleneck for your application. There's a lot more overhead to an http request than just the headers.

    You can also try alternative http stacks, like github.com/valyala/fasthttp, which strive to minimize allocations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部