-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
64 lines (59 loc) · 1.31 KB
/
request.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
package requests
import (
"bufio"
"bytes"
"io"
"log"
"net/http"
)
type Request struct {
url string
httpRequest *http.Request
httpClient http.Client
}
type HttpRequestInterface interface {
Send() HttpResultInterface
NewUpdateFile(readFile []byte) HttpResultInterface
Stream() chan []byte
}
func (c *Request) Send() HttpResultInterface {
if c.httpRequest == nil {
return NewResponse(nil)
}
respClient, err := c.httpClient.Do(c.httpRequest)
if err != nil {
log.Printf("httpClient.Do error: %v", err)
}
return NewResponse(respClient)
}
func (c *Request) Stream() chan []byte {
streamChan := make(chan []byte)
resp, ok := c.httpClient.Do(c.httpRequest)
if ok != nil {
log.Printf("httpClient.Do error: %v", ok)
} else {
go func() {
reader := bufio.NewReader(resp.Body)
for {
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
break
}
log.Printf("reader.ReadBytes error: %v", err)
}
streamChan <- line
}
}()
}
return streamChan
}
func (c *Request) NewUpdateFile(readFile []byte) HttpResultInterface {
res, err := http.Post(c.url, "multipart/form-data", bytes.NewReader(readFile))
if err != nil {
log.Printf("http.Post error: %v", err)
} else {
return &Response{Body: res.Body, Resp: res}
}
return HttpResultInterface(nil)
}