1package cert
2
3import (
4	"crypto/tls"
5	"log"
6	"reflect"
7	"time"
8)
9
10// watch monitors the result of the loadFn function for changes.
11func watch(ch chan []tls.Certificate, refresh time.Duration, path string, loadFn func(path string) (map[string][]byte, error)) {
12	once := refresh <= 0
13
14	// do not refresh more often than once a second to prevent busy loops
15	if refresh < time.Second {
16		refresh = time.Second
17	}
18
19	var last map[string][]byte
20	for {
21		next, err := loadFn(path)
22		if err != nil {
23			log.Printf("[ERROR] cert: Cannot load certificates from %s. %s", path, err)
24			time.Sleep(refresh)
25			continue
26		}
27
28		if reflect.DeepEqual(next, last) {
29			time.Sleep(refresh)
30			continue
31		}
32
33		certs, err := loadCertificates(next)
34		if err != nil {
35			log.Printf("[ERROR] cert: Cannot make certificates: %s", err)
36			continue
37		}
38
39		ch <- certs
40		last = next
41
42		if once {
43			return
44		}
45	}
46}
47