go-gemini/examples/stream.go

72 lines
1.3 KiB
Go
Raw Normal View History

2020-12-18 17:31:37 +00:00
// +build ignore
// This example illustrates a streaming Gemini server.
package main
import (
2021-01-10 06:13:07 +00:00
"context"
2020-12-18 17:31:37 +00:00
"fmt"
"log"
"time"
"git.sr.ht/~adnano/go-gemini"
2021-01-15 02:23:13 +00:00
"git.sr.ht/~adnano/go-gemini/certificate"
2020-12-18 17:31:37 +00:00
)
func main() {
2021-02-20 23:30:49 +00:00
certificates := &certificate.Store{}
certificates.Register("localhost")
if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
2020-12-18 17:31:37 +00:00
log.Fatal(err)
}
2021-02-20 23:30:49 +00:00
mux := &gemini.ServeMux{}
2021-02-18 01:35:27 +00:00
mux.HandleFunc("/", stream)
2021-02-20 23:30:49 +00:00
server := &gemini.Server{
Handler: mux,
ReadTimeout: 30 * time.Second,
WriteTimeout: 1 * time.Minute,
2021-02-23 13:43:41 +00:00
GetCertificate: certificates.Get,
2021-02-20 23:30:49 +00:00
}
2021-02-18 01:35:27 +00:00
ctx := context.Background()
if err := server.ListenAndServe(ctx); err != nil {
log.Fatal(err)
2020-12-18 17:31:37 +00:00
}
}
2021-01-10 06:13:07 +00:00
// stream writes an infinite stream to w.
2021-02-20 23:30:49 +00:00
func stream(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
2021-01-10 06:13:07 +00:00
ch := make(chan string)
2021-02-20 23:30:49 +00:00
ctx, cancel := context.WithCancel(ctx)
2021-01-10 06:13:07 +00:00
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)
2020-12-18 17:31:37 +00:00
for {
2021-01-10 06:13:07 +00:00
s, ok := <-ch
if !ok {
break
}
fmt.Fprintln(w, s)
if err := w.Flush(); err != nil {
2021-01-10 06:13:07 +00:00
cancel()
return
}
2020-12-18 17:31:37 +00:00
}
}