Skip to content

Commit 74fa8cd

Browse files
authored
Added convenience getters for single-value use (#71)
1 parent cf3b6be commit 74fa8cd

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

certificate.go

+22
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,28 @@ func (c *Certificate) PEM() (cert []byte, key []byte, err error) {
190190
return
191191
}
192192

193+
// CertPEM returns the certificate as a PEM buffer.
194+
// This method is useful in single-value context, for example when populating struct field.
195+
// Unlike the PEM() method, which handles errors, this method will panic if an error occurs.
196+
func (c *Certificate) CertPEM() []byte {
197+
cert, _, err := c.PEM()
198+
if err != nil {
199+
panic(err)
200+
}
201+
return cert
202+
}
203+
204+
// KeyPEM returns the private key as a PEM buffer.
205+
// This method is useful in single-value context, for example when populating struct field.
206+
// Unlike the PEM() method, which handles errors, this method will panic if an error occurs.
207+
func (c *Certificate) KeyPEM() []byte {
208+
_, key, err := c.PEM()
209+
if err != nil {
210+
panic(err)
211+
}
212+
return key
213+
}
214+
193215
// WritePEM writes the Certificate as certificate and private key PEM files.
194216
// Complete certificate chain (up to but not including root) is included for end-entity certificates.
195217
// A key pair and certificate will be generated at first call of any Certificate functions.

certificate_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -429,3 +429,11 @@ func TestCRLDistributionPoint(t *testing.T) {
429429
assert.Nil(t, err)
430430
assert.Equal(t, []string{"http://example.com/crl.pem"}, got.CRLDistributionPoints)
431431
}
432+
433+
func TestConvenienceGetters(t *testing.T) {
434+
input := Certificate{Subject: "CN=Joe"}
435+
cert, key, err := input.PEM()
436+
assert.Nil(t, err)
437+
assert.Equal(t, cert, input.CertPEM())
438+
assert.Equal(t, key, input.KeyPEM())
439+
}

0 commit comments

Comments
 (0)