go-gemini/examples/stream.go

81 lines
1.5 KiB
Go
Raw Normal View History

2020-12-18 10:31:37 -07:00
// +build ignore
// This example illustrates a streaming Gemini server.
package main
import (
2021-01-09 23:13:07 -07:00
"context"
2020-12-18 10:31:37 -07:00
"crypto/tls"
"crypto/x509/pkix"
"fmt"
"log"
"time"
"git.sr.ht/~adnano/go-gemini"
2021-01-14 19:23:13 -07:00
"git.sr.ht/~adnano/go-gemini/certificate"
2020-12-18 10:31:37 -07:00
)
func main() {
var server gemini.Server
if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
log.Fatal(err)
}
2021-01-25 08:59:50 -07:00
server.GetCertificate = func(hostname string) (tls.Certificate, error) {
2021-01-14 19:23:13 -07:00
return certificate.Create(certificate.CreateOptions{
2020-12-18 10:31:37 -07:00
Subject: pkix.Name{
CommonName: hostname,
},
DNSNames: []string{hostname},
Duration: 365 * 24 * time.Hour,
})
}
2021-02-17 18:35:27 -07:00
var mux gemini.ServeMux
mux.HandleFunc("/", stream)
server.Handler = &mux
2020-12-18 10:31:37 -07:00
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
2021-01-09 23:13:07 -07:00
// stream writes an infinite stream to w.
2021-02-09 07:45:10 -07: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-09 23:13:07 -07: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 10:31:37 -07:00
for {
2021-01-09 23:13:07 -07:00
s, ok := <-ch
if !ok {
break
}
fmt.Fprintln(w, s)
if err := flusher.Flush(); err != nil {
2021-01-09 23:13:07 -07:00
cancel()
return
}
2020-12-18 10:31:37 -07:00
}
}