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-01-14 20:12:07 -07:00
|
|
|
server.HandleFunc("localhost", stream)
|
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) {
|
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 := w.Flush(); err != nil {
|
|
|
|
cancel()
|
|
|
|
return
|
|
|
|
}
|
2020-12-18 10:31:37 -07:00
|
|
|
}
|
|
|
|
}
|