Created
October 28, 2014 06:57
-
-
Save yomusu/c718e016cf6afaedb25e to your computer and use it in GitHub Desktop.
Go:CloseNotify, Timeout example
This file contains hidden or 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" | |
"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