dongqiya9552 2016-06-15 12: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 12: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.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分