certchecker/certchecker.go
2024-07-25 17:03:53 +02:00

36 lines
760 B
Go

package certchecker
import (
"crypto/tls"
"fmt"
"time"
)
// Check checks if the certificate of the domain expires in less than notifyExpirationDays
// and returns an error if it does
func Check(domain string, notifyExpirationDays int) error {
conn, err := tls.Dial("tcp", domain+":443", nil)
if err != nil {
return err
}
defer conn.Close()
err = conn.Handshake()
if err != nil {
return err
}
err = conn.VerifyHostname(domain)
if err != nil {
return err
}
for _, certificate := range conn.ConnectionState().PeerCertificates {
expiresInDays := int(certificate.NotAfter.Sub(time.Now()).Hours() / 24)
if expiresInDays < notifyExpirationDays {
return fmt.Errorf("certificate expires in %d days", expiresInDays)
}
}
return nil
}