/
certs.go
54 lines (43 loc) · 1.18 KB
/
certs.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
package dashboard
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"strings"
"github.com/TykTechnologies/tyk-sync/clients/objects"
"github.com/ongoingio/urljoin"
)
func (c *Client) CreateCertificate(cert []byte) (string, error) {
fullPath := urljoin.Join(c.url, endpointCerts)
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(cert)))
err = writer.Close()
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", fullPath, body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", c.secret)
client := &http.Client{}
resp, err := client.Do(req)
rBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return "", fmt.Errorf("API Returned error: %v", string(rBody))
}
dbResp := objects.CertResponse{}
if err := json.Unmarshal(rBody, &dbResp); err != nil {
return "", err
}
if strings.ToLower(dbResp.Status) != "ok" {
return "", fmt.Errorf("API request completed, but with error: %v", dbResp.Message)
}
return dbResp.Id, nil
}