go-gemini/examples/stream.go

55 lines
1009 B
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
"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
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) {
2020-12-18 10:31:37 -07:00
for {
2021-02-23 13:31:41 -07:00
select {
case <-ctx.Done():
return
default:
2021-01-09 23:13:07 -07:00
}
2021-02-23 13:31:41 -07:00
fmt.Fprintln(w, time.Now().UTC())
if err := w.Flush(); err != nil {
2021-01-09 23:13:07 -07:00
return
}
2021-02-23 13:31:41 -07:00
time.Sleep(time.Second)
2020-12-18 10:31:37 -07:00
}
}