aboutsummaryrefslogtreecommitdiff
path: root/examples/stream.go
blob: 5b49b11130c83574de04895749eeb97d0466aec3 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// +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.ServeMux{}
	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) {
	ch := make(chan string)
	ctx, cancel := context.WithCancel(ctx)

	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)

	for {
		s, ok := <-ch
		if !ok {
			break
		}
		fmt.Fprintln(w, s)
		if err := w.Flush(); err != nil {
			cancel()
			return
		}
	}
}