Skip to content

Commit

Permalink
Added convenience getters for single-value use
Browse files Browse the repository at this point in the history
  • Loading branch information
tsaarni committed Oct 26, 2024
1 parent cf3b6be commit 429804e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
22 changes: 22 additions & 0 deletions certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,28 @@ func (c *Certificate) PEM() (cert []byte, key []byte, err error) {
return
}

// CertPEM returns the certificate as a PEM buffer.
// This method is useful in single-value context, for example when populating struct field.
// Unlike the PEM() method, which handles errors, this method will panic if an error occurs.
func (c *Certificate) CertPEM() []byte {
cert, _, err := c.PEM()
if err != nil {
panic(err)
}
return cert
}

// KeyPEM returns the private key as a PEM buffer.
// This method is useful in single-value context, for example when populating struct field.
// Unlike the PEM() method, which handles errors, this method will panic if an error occurs.
func (c *Certificate) KeyPEM() []byte {
_, key, err := c.PEM()
if err != nil {
panic(err)
}
return key
}

// WritePEM writes the Certificate as certificate and private key PEM files.
// Complete certificate chain (up to but not including root) is included for end-entity certificates.
// A key pair and certificate will be generated at first call of any Certificate functions.
Expand Down
8 changes: 8 additions & 0 deletions certificate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,3 +429,11 @@ func TestCRLDistributionPoint(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, []string{"http://example.com/crl.pem"}, got.CRLDistributionPoints)
}

func TestConvenienceGetters(t *testing.T) {
input := Certificate{Subject: "CN=Joe"}
cert, key, err := input.PEM()
assert.Nil(t, err)
assert.Equal(t, cert, input.CertPEM())
assert.Equal(t, key, input.KeyPEM())
}

0 comments on commit 429804e

Please sign in to comment.