LoginSignup
22
18

More than 5 years have passed since last update.

Go言語でTwitterのStreamingAPIっぽいのを作る

Posted at

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()))
    }
}

実行結果

952d4d28418b90aa35038a4fec3813d3.gif

おわり

色々エラーのハンドリングとか考えることは色々ありそうですが、思った以上に簡単に作れました。

22
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
18