Skip to content

Instantly share code, notes, and snippets.

@mix3
Created January 6, 2015 14:30
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 mix3/cdbf2b652dda7cbec78b to your computer and use it in GitHub Desktop.
Save mix3/cdbf2b652dda7cbec78b to your computer and use it in GitHub Desktop.
チャンクで返すサーバと、それを受けるクライアント
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)
}
}
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)
}
}
@mix3
Copy link
Author

mix3 commented Jan 6, 2015

$ go run chanked_client.go

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: text/plain; charset=utf-8
Date: Tue, 06 Jan 2015 14:29:31 GMT


2015-01-06 23:29:31.286051635 +0900 JST
2015-01-06 23:29:32.289838937 +0900 JST
2015-01-06 23:29:33.291992267 +0900 JST
2015-01-06 23:29:34.296553015 +0900 JST
2015-01-06 23:29:35.300829516 +0900 JST
.
.
.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment