-
Notifications
You must be signed in to change notification settings - Fork 0
/
a_http_request.go
84 lines (74 loc) · 2.24 KB
/
a_http_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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package pipe
import (
"fmt"
"github.com/imroc/req/v3"
"github.com/kataras/iris/v12"
"github.com/pkg/errors"
"net/http"
"strings"
)
type HttpRequestConfig struct {
Uri string `json:"uri,omitempty"` // 请求地址
Method string `json:"method,omitempty"` // 请求方法
PathParams map[string]string `json:"path_params,omitempty"` //
UrlParams map[string]any `json:"url_params,omitempty"` //
Body any `json:"body,omitempty"` //
Headers map[string]string `json:"headers,omitempty"` // 请求头设置
MustCode int `json:"must_code,omitempty"` // 响应码
}
func (c *HttpRequestConfig) GetMethod() string {
if len(c.Method) < 1 {
return http.MethodGet
}
return strings.ToUpper(c.Method)
}
func (c *HttpRequestConfig) GetMustCode() int {
if c.MustCode < 1 {
return 200
}
return c.MustCode
}
var (
// HttpRequest 发起http请求 必传 params
HttpRequest = &RunnerContext[any, *HttpRequestConfig, any, *req.Response]{
Name: "http请求",
Key: "http_request",
call: func(ctx iris.Context, origin any, params *HttpRequestConfig, db any, more ...any) *RunResp[*req.Response] {
if params == nil {
return NewPipeErr[*req.Response](PipePackParamsError)
}
// 格式验证
if len(params.Uri) < 1 {
return NewPipeErr[*req.Response](PipeParamsError)
}
// 设置请求头
r := req.R()
r.SetHeaders(params.Headers)
// 设置路径参数
if params.PathParams != nil {
r.SetPathParams(params.PathParams)
}
// 设置url query
if params.UrlParams != nil {
r.SetQueryParamsAnyType(params.UrlParams)
}
// 如果不是get 则可以设置body
if params.GetMethod() != http.MethodGet {
if params.Body != nil {
r.SetBody(params.Body)
}
}
resp, err := r.Send(params.GetMethod(), params.Uri)
if err != nil {
return NewPipeErr[*req.Response](err)
}
if resp.StatusCode != params.GetMustCode() {
return NewPipeErr[*req.Response](errors.New(fmt.Sprintf("请求需要 %d 响应码 但得到了 %d", params.GetMustCode(), resp.StatusCode)))
}
if resp.IsErrorState() {
return NewPipeErr[*req.Response](resp.Err)
}
return NewPipeResult[*req.Response](resp)
},
}
)