go-gemini/examples/stream.go

81 lines
1.5 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
"crypto/tls"
"crypto/x509/pkix"
"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() {
var server gemini.Server
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
log.Fatal(err)
}
2021-01-25 15:59:50 +00:00
server.GetCertificate = func(hostname string) (tls.Certificate, error) {
2021-01-15 02:23:13 +00:00
return certificate.Create(certificate.CreateOptions{
2020-12-18 17:31:37 +00:00
Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: 365 * 24 * time.Hour,
})
}
2021-02-18 01:35:27 +00:00
var mux gemini.ServeMux
mux.HandleFunc("/", stream)
server.Handler = &mux
2020-12-18 17:31:37 +00:00
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
2021-01-10 06:13:07 +00:00
// stream writes an infinite stream to w.
2021-02-09 14:45:10 +00:00
func stream(w gemini.ResponseWriter, r *gemini.Request) {
flusher, ok := w.(gemini.Flusher)
if !ok {
w.WriteHeader(gemini.StatusTemporaryFailure, "Internal error")
return
}
2021-01-10 06:13:07 +00:00
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)
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 := flusher.Flush(); err != nil {
2021-01-10 06:13:07 +00:00
cancel()
return
}
2020-12-18 17:31:37 +00:00
}
}