-
Notifications
You must be signed in to change notification settings - Fork 4
/
http_client.go
94 lines (74 loc) · 1.84 KB
/
http_client.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
package iot
import (
"github.com/go-resty/resty/v2"
"github.com/golang/glog"
"io/ioutil"
"net/url"
"os"
)
// 仅用于设备上传文件
type HttpClient interface {
UploadFile(filename, uri string) bool
DownloadFile(filename, uri string) bool
}
type httpClient struct {
client *resty.Client
}
func (client *httpClient) DownloadFile(fileName, downloadUrl string) bool {
glog.Infof("begin to download file %s, url = %s", fileName, downloadUrl)
fileName = smartFileName(fileName)
out, err := os.Create(fileName)
if err != nil {
glog.Errorf("create file in os failed ,file name %s", fileName)
return false
}
originalUri, err := url.ParseRequestURI(downloadUrl)
if err != nil {
glog.Errorf("parse request uri failed %v", err)
return false
}
resp, err := client.client.R().
SetHeader("Content-Type", "text/plain").
SetHeader("Host", originalUri.Host).
Get(downloadUrl)
if err != nil {
glog.Errorf("download file request failed %v", err)
return false
}
_, err = out.Write(resp.Body())
if err != nil {
glog.Errorf("write file failed")
return false
}
return true
}
func (client *httpClient) UploadFile(filename, uri string) bool {
filename = smartFileName(filename)
fileBytes, err := ioutil.ReadFile(filename)
if err != nil {
glog.Errorf("read file failed %v", err)
return false
}
originalUri, err := url.ParseRequestURI(uri)
if err != nil {
glog.Errorf("parse request uri failed %v", err)
return false
}
resp, err := client.client.R().
SetHeader("Content-Type", "text/plain").
SetHeader("Host", originalUri.Host).
SetBody(fileBytes).
Put(uri)
if err != nil {
glog.Errorf("upload request failed %v", err)
}
return resp.StatusCode() == 200
}
func CreateHttpClient() HttpClient {
client := resty.New()
client.SetRetryCount(3)
httpClient := &httpClient{
client: client,
}
return httpClient
}