仰望星辰工作室

miaopanel

miaopanel/ internal/paneltls/reloader.go 1.6 KB · 65 行 原始文件
1package paneltls
2
3import (
4 "crypto/tls"
5 "errors"
6 "sync"
7)
8
9// Reloader owns the certificate used by the panel's own TLS listener. It can
10// swap the pair at runtime so a freshly issued certificate takes effect
11// immediately, without restarting the process or dropping the listener.
12type Reloader struct {
13 mu sync.RWMutex
14 cert *tls.Certificate
15 certPath string
16 keyPath string
17}
18
19// NewReloader loads the initial pair and returns a reloadable holder.
20func NewReloader(certPath, keyPath string) (*Reloader, error) {
21 r := &Reloader{}
22 if err := r.Reload(certPath, keyPath); err != nil {
23 return nil, err
24 }
25 return r, nil
26}
27
28// Reload replaces the active certificate. The previous pair keeps serving in
29// flight handshakes until they finish.
30func (r *Reloader) Reload(certPath, keyPath string) error {
31 pair, err := tls.LoadX509KeyPair(certPath, keyPath)
32 if err != nil {
33 return err
34 }
35 r.mu.Lock()
36 r.cert = &pair
37 r.certPath = certPath
38 r.keyPath = keyPath
39 r.mu.Unlock()
40 return nil
41}
42
43// Paths reports the pair currently in use.
44func (r *Reloader) Paths() (string, string) {
45 r.mu.RLock()
46 defer r.mu.RUnlock()
47 return r.certPath, r.keyPath
48}
49
50// TLSConfig returns a config that resolves the certificate on every handshake,
51// which is what makes Reload take effect without a restart.
52func (r *Reloader) TLSConfig() *tls.Config {
53 return &tls.Config{
54 MinVersion: tls.VersionTLS12,
55 NextProtos: []string{"http/1.1"},
56 GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
57 r.mu.RLock()
58 defer r.mu.RUnlock()
59 if r.cert == nil {
60 return nil, errors.New("尚未加载证书")
61 }
62 return r.cert, nil
63 },
64 }
65}