/
cert.go
116 lines (89 loc) · 2.22 KB
/
cert.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package dashboard
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"github.com/TykTechnologies/tyk-operator/pkg/client"
)
type Cert struct{}
type CertificateList struct {
CertIDs []string `json:"certs"`
Pages int `json:"pages"`
}
// All returns a list of all certificates ID's
func (c Cert) All(ctx context.Context) ([]string, error) {
res, err := client.Get(ctx, endpointCerts, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, client.Error(res)
}
var o CertificateList
err = client.JSON(res, &o)
if err != nil {
return nil, err
}
return o.CertIDs, nil
}
func (c Cert) Exists(ctx context.Context, id string) bool {
res, err := client.Get(ctx, client.Join(endpointCerts, id), nil)
if err != nil {
client.LError(ctx, err, "failed to get certificate")
return false
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
client.LError(ctx, client.Error(res), "Unexpected status")
return false
}
return true
}
func (c Cert) Delete(ctx context.Context, id string) error {
res, err := client.Delete(ctx, client.Join(endpointCerts, id), nil)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("expected 200 OK, got %d %s", res.StatusCode, http.StatusText(res.StatusCode))
}
return nil
}
func (c Cert) Upload(ctx context.Context, key, crt []byte) (id string, err error) {
combined := make([]byte, 0)
combined = append(combined, key...)
combined = append(combined, crt...)
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("cert", "cert.pem")
if err != nil {
return "", err
}
_, err = io.Copy(part, io.NopCloser(bytes.NewReader(combined)))
err = writer.Close()
if err != nil {
return "", err
}
res, err := client.Post(ctx, endpointCerts, body, client.SetHeaders(
map[string]string{
"Content-Type": writer.FormDataContentType(),
},
))
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return "", client.Error(res)
}
dbResp := CertResponse{}
if err := client.JSON(res, &dbResp); err != nil {
return "", err
}
return dbResp.Id, nil
}