forked from gokalkan/gokalkan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathw_load_cert_from_url.go
More file actions
75 lines (58 loc) · 1.35 KB
/
Copy pathw_load_cert_from_url.go
File metadata and controls
75 lines (58 loc) · 1.35 KB
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
package gokalkan
import (
"context"
"fmt"
"io"
"net/http"
"os"
)
// LoadCertFromURL загружает сертификат по url в хранилище.
func (cli *Client) LoadCertFromURL(ctx context.Context, url string, t KCCertType) (err error) {
tmpCertFile, err := os.CreateTemp("", "tmp.cert.*.crt")
if err != nil {
return err
}
filename := tmpCertFile.Name()
defer func() {
_ = os.Remove(filename)
}()
defer func() {
_ = tmpCertFile.Close()
}()
err = cli.download(ctx, url, tmpCertFile)
if err != nil {
return err
}
err = tmpCertFile.Close()
if err != nil {
return err
}
err = cli.kc.KCX509LoadCertificateFromFile(filename, t)
if err != nil {
return err
}
return nil
}
func (cli *Client) download(ctx context.Context, url string, w io.Writer) (err error) {
req, err := http.NewRequestWithContext(ctx, "GET", url, http.NoBody)
if err != nil {
return fmt.Errorf("%w: %s", ErrHTTPCli, err)
}
req.Close = true
resp, err := cli.c.Do(req)
if err != nil {
return fmt.Errorf("%w: %s", ErrHTTPCli, err)
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, resp.Body)
return fmt.Errorf("%w: bad status: %d", ErrHTTPCli, resp.StatusCode)
}
_, err = io.Copy(w, resp.Body)
if err != nil {
return fmt.Errorf("%w: %s", ErrHTTPCli, err)
}
return nil
}