-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcertcache.go
77 lines (61 loc) · 1.47 KB
/
certcache.go
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
72
73
74
75
76
77
package main
import (
"context"
"crypto/tls"
"errors"
"sync"
"golang.org/x/crypto/acme/autocert"
)
var errUninitializedCert = errors.New("certificate not yet initialized")
// certRetriever stores an HTTPS certificate and implements the GetCertificate
// function signature, which allows our Web servers to retrieve the
// certificate when clients connect:
// https://pkg.go.dev/crypto/tls#Config
type certRetriever struct {
sync.Mutex // Guards cert.
cert *tls.Certificate
}
func (c *certRetriever) set(cert *tls.Certificate) {
c.Lock()
defer c.Unlock()
c.cert = cert
}
func (c *certRetriever) get(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
c.Lock()
defer c.Unlock()
if c.cert == nil {
return nil, errUninitializedCert
}
return c.cert, nil
}
// certCache implements the autocert.Cache interface.
type certCache struct {
sync.RWMutex // Guards cache.
cache map[string][]byte
}
func newCertCache() *certCache {
return &certCache{
cache: make(map[string][]byte),
}
}
func (c *certCache) Get(ctx context.Context, key string) ([]byte, error) {
c.RLock()
defer c.RUnlock()
cert, exists := c.cache[key]
if !exists {
return nil, autocert.ErrCacheMiss
}
return cert, nil
}
func (c *certCache) Put(ctx context.Context, key string, data []byte) error {
c.Lock()
defer c.Unlock()
c.cache[key] = data
return nil
}
func (c *certCache) Delete(ctx context.Context, key string) error {
c.Lock()
defer c.Unlock()
delete(c.cache, key)
return nil
}