Skip to content

Instantly share code, notes, and snippets.

@yomusu
Created October 28, 2014 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yomusu/c718e016cf6afaedb25e to your computer and use it in GitHub Desktop.
Save yomusu/c718e016cf6afaedb25e to your computer and use it in GitHub Desktop.
Go:CloseNotify, Timeout example
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func outln(w http.ResponseWriter, mes string) {
w.Write([]byte(mes))
w.Write([]byte("\n"))
w.(http.Flusher).Flush()
log.Println(mes)
}
func handler(w http.ResponseWriter, r *http.Request) {
// Transfer-Encoding: chunked
w.WriteHeader(http.StatusOK)
outln(w, "start")
// for over
times := 5
// for TimeOut
//times := 10
// メッセージを送る人
ch := make(chan string)
go func() {
for i := 0; i < times; i++ {
time.Sleep(time.Second * 1)
ch <- fmt.Sprintf("hoge:%d", i)
}
close(ch)
}()
// 時間制限は10秒
timeout := time.After(time.Second * 10)
// 通信切断されたら抜ける
closeNotify := w.(http.CloseNotifier).CloseNotify()
// 何かしら結果が出るまでループする
Loop:
for {
select {
case mes, ok := <-ch:
if ok {
outln(w, mes)
} else {
outln(w, "message is over")
break Loop
}
case <-closeNotify:
log.Println("session closed")
break Loop
case <-timeout:
outln(w, "process timeout")
break Loop
}
}
outln(w, "bye")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8085", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment