[Go] Chunked Transferで返すHTTPサーバー

HTTPのストリーミングサーバーのいわゆるLong Pollingってヤツ。

net/httpを使う普通のやり方に加えて、
ポイントは

  1. WriteHeaderを先に呼ぶ
  2. http.ResponseWriterをFlushする

ってこと。
Transfer-Encodingヘッダをchunkedにするとか、
Content-Lengthヘッダをセットしてはいけないとか、
は、勝手にやってくれる。


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)
}
view raw main.go hosted with ❤ by GitHub
これを起動したならば、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

が表示される!

コメント

このブログの人気の投稿

Android・・・テキスト描画あれこれ, ascent(), descent()等

nginxでlocalhostとしてアクセスをサーバーに転送する方法

Android:stateに応じてTextの色を変更する・・・ColorStateList