[Go] Chunked Transferで返すHTTPサーバー
HTTPのストリーミングサーバーのいわゆるLong Pollingってヤツ。
net/httpを使う普通のやり方に加えて、
ポイントは
ってこと。
Transfer-Encodingヘッダをchunkedにするとか、
Content-Lengthヘッダをセットしてはいけないとか、
は、勝手にやってくれる。
これを起動したならば、curlコマンドで試してみませう。
curl -v http://localhost:8085/
ヘッダが表示され、
< HTTP/1.1 200 OK
< Date: Fri, 24 Oct 2014 05:14:14 GMT
< Content-Type: text/plain; charset=utf-8
< Transfer-Encoding: chunked
その5秒後に
one
その5秒後に
two
が表示される!
net/httpを使う普通のやり方に加えて、
ポイントは
- WriteHeaderを先に呼ぶ
- http.ResponseWriterをFlushする
ってこと。
Transfer-Encodingヘッダをchunkedにするとか、
Content-Lengthヘッダをセットしてはいけないとか、
は、勝手にやってくれる。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"time" | |
) | |
func handler(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
w.(http.Flusher).Flush() | |
time.Sleep(2000 * time.Millisecond) | |
fmt.Fprintln(w, "one") | |
w.(http.Flusher).Flush() | |
time.Sleep(2000 * time.Millisecond) | |
fmt.Fprintln(w, "two") | |
w.(http.Flusher).Flush() | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(":8085", nil) | |
} |
curl -v http://localhost:8085/
ヘッダが表示され、
< HTTP/1.1 200 OK
< Date: Fri, 24 Oct 2014 05:14:14 GMT
< Content-Type: text/plain; charset=utf-8
< Transfer-Encoding: chunked
その5秒後に
one
その5秒後に
two
が表示される!
コメント
コメントを投稿