aboutsummaryrefslogtreecommitdiff
path: root/examples/stream.go
blob: 6f29fb40cadaf1994963c2914e1dce0717aeb65a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// +build ignore

// This example illustrates a streaming Gemini server.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"git.sr.ht/~adnano/go-gemini"
	"git.sr.ht/~adnano/go-gemini/certificate"
)

func main() {
	certificates := &certificate.Store{}
	certificates.Register("localhost")
	if err := certificates.Load("/var/lib/gemini/certs"); err != nil {
		log.Fatal(err)
	}

	mux := &gemini.Mux{}
	mux.HandleFunc("/", stream)

	server := &gemini.Server{
		Handler:        mux,
		ReadTimeout:    30 * time.Second,
		WriteTimeout:   1 * time.Minute,
		GetCertificate: certificates.Get,
	}

	ctx := context.Background()
	if err := server.ListenAndServe(ctx); err != nil {
		log.Fatal(err)
	}
}

// stream writes an infinite stream to w.
func stream(ctx context.Context, w gemini.ResponseWriter, r *gemini.Request) {
	for {
		select {
		case <-ctx.Done():
			return
		default:
		}
		fmt.Fprintln(w, time.Now().UTC())
		if err := w.Flush(); err != nil {
			return
		}
		time.Sleep(time.Second)
	}
}