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-01-15 03:12:07 +00:00
|
|
|
server.HandleFunc("localhost", stream)
|
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) {
|
2021-02-17 16:44:11 +00:00
|
|
|
flusher, ok := w.(gemini.Flusher)
|
|
|
|
if !ok {
|
2021-02-17 18:39:18 +00:00
|
|
|
w.WriteHeader(gemini.StatusTemporaryFailure, "Internal error")
|
2021-02-17 16:44:11 +00:00
|
|
|
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)
|
2021-02-17 16:44:11 +00:00
|
|
|
if err := flusher.Flush(); err != nil {
|
2021-01-10 06:13:07 +00:00
|
|
|
cancel()
|
|
|
|
return
|
|
|
|
}
|
2020-12-18 17:31:37 +00:00
|
|
|
}
|
|
|
|
}
|