go-gemini/examples/stream.go
2021-02-20 18:30:49 -05:00

77 lines
1.4 KiB
Go

// +build ignore
// This example illustrates a streaming Gemini server.
package main
import (
"context"
"fmt"
"log"
"time"
"git.sr.ht/~adnano/go-gemini"
"git.sr.ht/~adnano/go-gemini/certificate"
)
func main() {
certificates := &certificate.Store{}
certificates.Register("localhost")
if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
log.Fatal(err)
}
mux := &gemini.ServeMux{}
mux.HandleFunc("/", stream)
server := &gemini.Server{
Handler: mux,
ReadTimeout: 30 * time.Second,
WriteTimeout: 1 * time.Minute,
GetCertificate: certificates.GetCertificate,
}
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
// stream writes an infinite stream to w.
func stream(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
flusher, ok := w.(gemini.Flusher)
if !ok {
w.WriteHeader(gemini.StatusTemporaryFailure, "Internal error")
return
}
ch := make(chan string)
ctx, cancel := context.WithCancel(ctx)
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 {
s, ok := <-ch
if !ok {
break
}
fmt.Fprintln(w, s)
if err := flusher.Flush(); err != nil {
cancel()
return
}
}
}