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
|
|
|
"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() {
|
2021-02-20 16:30:49 -07:00
|
|
|
certificates := &certificate.Store{}
|
|
|
|
certificates.Register("localhost")
|
|
|
|
if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
|
2020-12-18 10:31:37 -07:00
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2021-02-20 16:30:49 -07:00
|
|
|
mux := &gemini.ServeMux{}
|
2021-02-17 18:35:27 -07:00
|
|
|
mux.HandleFunc("/", stream)
|
2021-02-20 16:30:49 -07:00
|
|
|
|
|
|
|
server := &gemini.Server{
|
|
|
|
Handler: mux,
|
|
|
|
ReadTimeout: 30 * time.Second,
|
|
|
|
WriteTimeout: 1 * time.Minute,
|
2021-02-23 06:43:41 -07:00
|
|
|
GetCertificate: certificates.Get,
|
2021-02-20 16:30:49 -07:00
|
|
|
}
|
2021-02-17 18:35:27 -07:00
|
|
|
|
2021-02-22 19:16:13 -07:00
|
|
|
ctx := context.Background()
|
|
|
|
if err := server.ListenAndServe(ctx); err != nil {
|
|
|
|
log.Fatal(err)
|
2020-12-18 10:31:37 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-09 23:13:07 -07:00
|
|
|
// stream writes an infinite stream to w.
|
2021-02-20 16:30:49 -07:00
|
|
|
func stream(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
|
2021-01-09 23:13:07 -07:00
|
|
|
ch := make(chan string)
|
2021-02-20 16:30:49 -07:00
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
2021-01-09 23:13:07 -07:00
|
|
|
|
|
|
|
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)
|
2021-02-22 18:07:15 -07:00
|
|
|
if err := w.Flush(); err != nil {
|
2021-01-09 23:13:07 -07:00
|
|
|
cancel()
|
|
|
|
return
|
|
|
|
}
|
2020-12-18 10:31:37 -07:00
|
|
|
}
|
|
|
|
}
|