package paneltls import ( "crypto/tls" "errors" "sync" ) // Reloader owns the certificate used by the panel's own TLS listener. It can // swap the pair at runtime so a freshly issued certificate takes effect // immediately, without restarting the process or dropping the listener. type Reloader struct { mu sync.RWMutex cert *tls.Certificate certPath string keyPath string } // NewReloader loads the initial pair and returns a reloadable holder. func NewReloader(certPath, keyPath string) (*Reloader, error) { r := &Reloader{} if err := r.Reload(certPath, keyPath); err != nil { return nil, err } return r, nil } // Reload replaces the active certificate. The previous pair keeps serving in // flight handshakes until they finish. func (r *Reloader) Reload(certPath, keyPath string) error { pair, err := tls.LoadX509KeyPair(certPath, keyPath) if err != nil { return err } r.mu.Lock() r.cert = &pair r.certPath = certPath r.keyPath = keyPath r.mu.Unlock() return nil } // Paths reports the pair currently in use. func (r *Reloader) Paths() (string, string) { r.mu.RLock() defer r.mu.RUnlock() return r.certPath, r.keyPath } // TLSConfig returns a config that resolves the certificate on every handshake, // which is what makes Reload take effect without a restart. func (r *Reloader) TLSConfig() *tls.Config { return &tls.Config{ MinVersion: tls.VersionTLS12, NextProtos: []string{"http/1.1"}, GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { r.mu.RLock() defer r.mu.RUnlock() if r.cert == nil { return nil, errors.New("尚未加载证书") } return r.cert, nil }, } }