aboutsummaryrefslogtreecommitdiff
path: root/examples/stream.go
blob: 74c78e523b2c41bb7c8b9dd57644c6fce8649363 (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"
	"crypto/tls"
	"crypto/x509/pkix"
	"fmt"
	"log"
	"time"

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

func main() {
	var server gemini.Server
	if err := server.Certificates.Load("/var/lib/gemini/certs"); err != nil {
		log.Fatal(err)
	}
	server.CreateCertificate = func(hostname string) (tls.Certificate, error) {
		return certificate.Create(certificate.CreateOptions{
			Subject: pkix.Name{
				CommonName: hostname,
			},
			DNSNames: []string{hostname},
			Duration: 365 * 24 * time.Hour,
		})
	}

	server.HandleFunc("localhost", stream)
	if err := server.ListenAndServe(); err != nil {
		log.Fatal(err)
	}
}

// stream writes an infinite stream to w.
func stream(w *gemini.ResponseWriter, r *gemini.Request) {
	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)

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