examples/stream: Simplify
This commit is contained in:
parent
1aa85d0683
commit
09e3393e4c
@ -39,33 +39,16 @@ func main() {
|
|||||||
|
|
||||||
// stream writes an infinite stream to w.
|
// stream writes an infinite stream to w.
|
||||||
func stream(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
func stream(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
||||||
ch := make(chan string)
|
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
|
||||||
|
|
||||||
go func(ctx context.Context) {
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
ch <- fmt.Sprint(time.Now().UTC())
|
}
|
||||||
|
fmt.Fprintln(w, time.Now().UTC())
|
||||||
|
if err := w.Flush(); err != nil {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
time.Sleep(time.Second)
|
time.Sleep(time.Second)
|
||||||
}
|
}
|
||||||
// Close channel when finished.
|
|
||||||
// In this example this will never be reached.
|
|
||||||
close(ch)
|
|
||||||
}(ctx)
|
|
||||||
|
|
||||||
for {
|
|
||||||
s, ok := <-ch
|
|
||||||
if !ok {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
fmt.Fprintln(w, s)
|
|
||||||
if err := w.Flush(); err != nil {
|
|
||||||
cancel()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user