Update examples/stream.go
This commit is contained in:
parent
5e977250ec
commit
24026422b2
@ -5,6 +5,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509/pkix"
|
"crypto/x509/pkix"
|
||||||
"fmt"
|
"fmt"
|
||||||
@ -35,10 +36,35 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stream writes an infinite stream to w.
|
||||||
func stream(w *gemini.ResponseWriter, r *gemini.Request) {
|
func stream(w *gemini.ResponseWriter, r *gemini.Request) {
|
||||||
|
ch := make(chan string)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
|
go func(ctx context.Context) {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
ch <- fmt.Sprint(time.Now().UTC())
|
||||||
|
}
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
}
|
||||||
|
// Close channel when finished.
|
||||||
|
// In this example this will never be reached.
|
||||||
|
close(ch)
|
||||||
|
}(ctx)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
fmt.Fprintln(w, time.Now().UTC())
|
s, ok := <-ch
|
||||||
w.Flush()
|
if !ok {
|
||||||
time.Sleep(time.Second)
|
break
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w, s)
|
||||||
|
if err := w.Flush(); err != nil {
|
||||||
|
cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user