Created
January 6, 2015 14:30
-
-
Save mix3/cdbf2b652dda7cbec78b to your computer and use it in GitHub Desktop.
チャンクで返すサーバと、それを受けるクライアント
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 ( | |
"bufio" | |
"fmt" | |
"log" | |
"net/http" | |
"net/http/httputil" | |
"os" | |
) | |
func main() { | |
client := http.Client{} | |
res, err := client.Get("http://127.0.0.1:12345/") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer res.Body.Close() | |
ret, _ := httputil.DumpResponse(res, false) | |
fmt.Println(string(ret)) | |
scanner := bufio.NewScanner(res.Body) | |
for scanner.Scan() { | |
fmt.Println(scanner.Text()) | |
} | |
if err := scanner.Err(); err != nil { | |
fmt.Fprintln(os.Stderr, "reading standard input:", err) | |
} | |
} |
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 ChankedServer(w http.ResponseWriter, req *http.Request) { | |
closed := false | |
closedCh := make(chan struct{}) | |
go func() { | |
notify := w.(http.CloseNotifier).CloseNotify() | |
closed = <-notify | |
}() | |
go func() { | |
for { | |
switch { | |
case closed: | |
closedCh <- struct{}{} | |
return | |
default: | |
fmt.Fprintf(w, "%v\n", time.Now()) | |
w.(http.Flusher).Flush() | |
time.Sleep(time.Second * 1) | |
} | |
} | |
}() | |
<-closedCh | |
} | |
func main() { | |
http.HandleFunc("/", ChankedServer) | |
err := http.ListenAndServe(":12345", nil) | |
if err != nil { | |
log.Fatal("ListenAndServe: ", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ go run chanked_client.go