-
Notifications
You must be signed in to change notification settings - Fork 1
/
http_run_handler.go
101 lines (84 loc) · 2.35 KB
/
http_run_handler.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
// SPDX-FileCopyrightText: 2024 M. Shulhan <ms@kilabit.info>
// SPDX-License-Identifier: GPL-3.0-or-later
package gorankusu
import (
"bytes"
"fmt"
"io"
"net/http"
libhttp "git.sr.ht/~shulhan/pakakeh.go/lib/http"
)
// HTTPRunHandler define the function type that will be called when client
// send request to run the HTTP target.
type HTTPRunHandler func(rr *RunRequest) (runres *RunResponse, err error)
// DefaultHTTPRun default [HTTPTarget.Run] handler that generate
// [http.Request], send it to the target, and store and dump them into
// [RunResponse].
func DefaultHTTPRun() HTTPRunHandler {
return func(rr *RunRequest) (res *RunResponse, err error) {
var (
logp = `DefaultHTTPRun`
httpcOpts = libhttp.ClientOptions{
ServerURL: rr.Target.BaseURL,
AllowInsecure: true,
}
httpc = libhttp.NewClient(httpcOpts)
params any
)
if !rr.HTTPTarget.WithRawBody {
rr.HTTPTarget.paramsToPath()
params, err = rr.HTTPTarget.ParamsConverter(&rr.HTTPTarget)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
}
var (
headers = http.Header{}
key string
fi FormInput
)
for key, fi = range rr.Target.Headers {
if len(fi.Value) != 0 {
headers.Set(key, fi.Value)
}
}
for key, fi = range rr.HTTPTarget.Headers {
if len(fi.Value) != 0 {
headers.Set(key, fi.Value)
}
}
var (
clientReq = libhttp.ClientRequest{
Method: rr.HTTPTarget.Method,
Path: rr.HTTPTarget.Path,
Type: rr.HTTPTarget.RequestType,
Header: headers,
Params: params,
}
httpRequest *http.Request
)
httpRequest, err = httpc.GenerateHTTPRequest(clientReq)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
if rr.HTTPTarget.WithRawBody {
httpRequest.Body = io.NopCloser(bytes.NewReader(rr.HTTPTarget.RawBody))
httpRequest.ContentLength = int64(len(rr.HTTPTarget.RawBody))
}
res = &RunResponse{}
err = res.SetHTTPRequest(rr.HTTPTarget.RequestDumper, httpRequest)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
var clientRes *libhttp.ClientResponse
clientRes, err = httpc.Do(httpRequest)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
err = res.SetHTTPResponse(rr.HTTPTarget.ResponseDumper, clientRes.HTTPResponse)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
return res, nil
}
}