This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
forked from s7techlab/hlf-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 2
/
certificate.go
73 lines (58 loc) · 1.62 KB
/
certificate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package ca
import (
"context"
"crypto/x509"
"encoding/pem"
"fmt"
"net/http"
"net/url"
"github.com/pkg/errors"
"github.com/atomyze-ru/hlf-sdk-go/api/ca"
)
const endpointCertificateList = "%s/api/v1/certificates%s"
func (c *core) CertificateList(ctx context.Context, opts ...ca.CertificateListOpt) ([]*x509.Certificate, error) {
var (
reqUrl string
err error
)
u := url.Values{}
for _, opt := range opts {
if err = opt(&u); err != nil {
return nil, errors.Wrap(err, `failed to apply opt`)
}
}
if v := u.Encode(); v == `` {
reqUrl = fmt.Sprintf(endpointCertificateList, c.config.Host, ``)
} else {
reqUrl = fmt.Sprintf(endpointCertificateList, c.config.Host, `?`+v)
}
req, err := http.NewRequest(http.MethodGet, reqUrl, nil)
if err != nil {
return nil, errors.Wrap(err, `failed to create request`)
}
if err = c.setAuthToken(req, nil); err != nil {
return nil, errors.Wrap(err, `failed to set authorization token`)
}
req = req.WithContext(ctx)
resp, err := c.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, `failed to process request`)
}
var certResponse ca.ResponseCertificateList
if err = c.processResponse(resp, &certResponse, http.StatusOK); err != nil {
return nil, err
}
certs := make([]*x509.Certificate, len(certResponse.Certs))
for i, v := range certResponse.Certs {
b, _ := pem.Decode([]byte(v.PEM))
if b == nil {
return nil, errors.Errorf("failed to parse PEM block: %s", v)
}
if cert, err := x509.ParseCertificate(b.Bytes); err != nil {
return nil, errors.Wrap(err, `failed to parse certificate`)
} else {
certs[i] = cert
}
}
return certs, nil
}