dongye9228 2014-09-25 08:25
浏览 125
已采纳

HTTP ResponseWriter的写函数是否可以在Go中缓冲?

Assume that we have a function handling an HTTP Request, something like:

func handler(w http.ResponseWriter,  r *http.Request) {
    w.Write([]byte("first piece of data"))
    // do something
    w.Write([]byte("second piece of data"))
}  

I'm wondering that if the first call to w.Write() is flushed to client or not?

If it is flushed, then we actually responses to clients twice, this is strange because how can we determine Content-Length before the second call to write?

If it is not flushed (say the data is buffered locally), then what if we write a huge amount of data at the first call? (will that stack overflow?)

Any explanation will be appreciated! :)

  • 写回答

1条回答 默认 最新

  • dszn2485 2014-09-25 12:54
    关注

    I'm wondering that if the first call to w.Write() is flushed to client or not?

    net/http's default ResonseWriter has a (currently 4KB) large output buffer over the net.Conn it writes to. Additionally, the OS normally will buffer writes to a socket. So in most cases some kind of buffering takes place.

    If it is flushed, then we actually responses to clients twice, this is strange because how can we determine Content-Length before the second call to write?

    Well there's HTTP 1.1 which allows persistent connections. Such responses usually don't include a Content-Length header. Additionally, there's HTTP trailers.

    If your client does not support HTTP 1.1 and persistent connections they will have some sort of read timeout, during this time you can write to the connection as many times as you like; it's one response.

    This has more to do with the nature of TCP sockets and HTTP implementations than Go.

    If it is not flushed (say the data is buffered locally), then what if we write a huge amount of data at the first call? (will that stack overflow?)

    No, allocating a buffer on the stack makes no sense – the buffer's body will live on the heap. If you hit your per-process memory limit your application will panic "out of memory".

    See also:

    Edit to answer your question in the comments:

    Chunked Transfer Encoding is part of the HTTP 1.1 specification and not supported in HTTP 1.0.

    Edit to clarify:

    As long as the total time it takes you to write both parts of your response does not exceed your client's read time out, and you don't specify a Content-Length header you just write your response and then close the connection. That's totally OK and not "hacky".

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

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决