Server側
普通にhttpで受けてhttp.ResponseWriter
をwriteしてすぐにw.(http.Flusher)Flush()
するだけ。
main_server.go
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", helloStreaming)
http.ListenAndServe(":8000", nil)
}
func helloStreaming(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
// TODO: 5秒helloを繰り返す適当なコード
for i := 0; i < 5; i++ {
w.Write([]byte("hello\n"))
w.(http.Flusher).Flush()
time.Sleep(1 * time.Second)
}
fmt.Fprintf(w, "hello end\n")
}
Client側
クライアント側は、さっきのサーバーへ普通にhttp.Get()
してhttp.Response.Body
に書き込みがあったら反応するようにするだけ。
main_client.go
package main
import (
"fmt"
"net/http"
"log"
"bufio"
)
func main() {
res, err := http.Get("http://localhost:8000")
if err != nil {
log.Fatalln(err)
}
scanner := bufio.NewScanner(res.Body)
for scanner.Scan() {
fmt.Println(string(scanner.Bytes()))
}
}
実行結果
おわり
色々エラーのハンドリングとか考えることは色々ありそうですが、思った以上に簡単に作れました。