-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtask_http.go
116 lines (103 loc) · 2.36 KB
/
task_http.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 rmq
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
type HttpTask struct {
Url string `json:"url"`
Method string `json:"method"`
Header map[string]string `json:"header,omitempty"`
Body json.RawMessage `json:"body,omitempty"` // 因为json序列号,保证消息好看一点
msg *Message
}
func NewHttpTaskGet(format string, arg ...any) *HttpTask {
return &HttpTask{
Url: fmt.Sprintf(format, arg...),
Method: http.MethodGet,
}
}
func NewHttpTaskJsonPost(url string, data any) *HttpTask {
body, _ := json.Marshal(data)
return &HttpTask{
Url: url,
Method: http.MethodPost,
Header: map[string]string{
"Content-Type": "application/json",
},
Body: body,
}
}
func NewHttpTaskPostPostForm(url string, data url.Values) *HttpTask {
return &HttpTask{
Url: url,
Method: http.MethodPost,
Header: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
Body: []byte(data.Encode()),
}
}
func (h *HttpTask) SetHeaders(headers map[string]string) *HttpTask {
for k, v := range headers {
h.Header[k] = v
}
return h
}
func (h *HttpTask) SetHeader(k, v string) *HttpTask {
h.Header[k] = v
return h
}
func (h *HttpTask) SetBody(data []byte) *HttpTask {
h.Body = data
return h
}
func (h *HttpTask) SetMethod(method string) *HttpTask {
h.Method = method
return h
}
func (h *HttpTask) Message() (msg *Message, err error) {
msg, err = NewMsg().SetTask(h)
return
}
func (h *HttpTask) TaskName() string {
return "httpTask"
}
func (h *HttpTask) Scan(src []byte) (err error) {
return json.Unmarshal(src, &h)
}
func (h *HttpTask) Load(ctx context.Context, msg *Message) (err error) {
h.msg = msg
return
}
func (h *HttpTask) Run(ctx context.Context) (result string, err error) {
var (
req *http.Request
resp *http.Response
body []byte
)
if req, err = http.NewRequestWithContext(ctx, h.Method, h.Url, bytes.NewReader(h.Body)); err != nil {
return
}
for k, v := range h.Header {
req.Header.Set(k, v)
}
client := http.Client{Timeout: time.Duration(h.msg.Meta.Timeout) * time.Second}
if resp, err = client.Do(req); err != nil {
return
}
defer resp.Body.Close()
if body, err = io.ReadAll(resp.Body); err != nil {
return
}
if resp.StatusCode != 200 {
err = fmt.Errorf("请求失败:%s", string(body))
}
result = string(body)
return
}