-
Notifications
You must be signed in to change notification settings - Fork 1
/
http_attack_handler.go
82 lines (66 loc) · 2.14 KB
/
http_attack_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
// SPDX-FileCopyrightText: 2024 M. Shulhan <ms@kilabit.info>
// SPDX-License-Identifier: GPL-3.0-or-later
package gorankusu
import (
"encoding/json"
"fmt"
libhttp "git.sr.ht/~shulhan/pakakeh.go/lib/http"
vegeta "github.com/tsenart/vegeta/v12/lib"
)
// HTTPAttackHandler define the function type that will be called when client
// send request to attack HTTP target.
type HTTPAttackHandler func(rr *RunRequest) vegeta.Targeter
// DefaultHTTPAttack define the default value for [HTTPTarget.Attack] handler
// that return [vegeta.Targeter].
func DefaultHTTPAttack() HTTPAttackHandler {
return func(rr *RunRequest) vegeta.Targeter {
var err error
rr.HTTPTarget.Lock()
defer rr.HTTPTarget.Unlock()
rr.HTTPTarget.paramsToPath()
var vegetaTarget = vegeta.Target{
Method: string(rr.HTTPTarget.Method),
URL: fmt.Sprintf(`%s%s`, rr.Target.BaseURL, rr.HTTPTarget.Path),
Header: rr.HTTPTarget.Headers.ToHTTPHeader(),
}
var contentType = rr.HTTPTarget.RequestType.String()
if len(contentType) != 0 {
vegetaTarget.Header.Set(libhttp.HeaderContentType, contentType)
}
if rr.HTTPTarget.WithRawBody {
vegetaTarget.Body = rr.HTTPTarget.RawBody
} else {
switch rr.HTTPTarget.RequestType {
case libhttp.RequestTypeQuery:
var q = rr.HTTPTarget.Params.ToURLValues().Encode()
if len(q) > 0 {
vegetaTarget.URL += `?` + q
}
case libhttp.RequestTypeForm:
var form = rr.HTTPTarget.Params.ToURLValues().Encode()
vegetaTarget.Body = []byte(form)
case libhttp.RequestTypeJSON:
var mapStringAny = rr.HTTPTarget.Params.ToJSONObject()
vegetaTarget.Body, err = json.Marshal(mapStringAny)
case libhttp.RequestTypeMultipartForm:
var (
params map[string][]byte
body string
)
params = rr.HTTPTarget.Params.ToMultipartFormData()
contentType, body, err = libhttp.GenerateFormData(params)
if err == nil {
vegetaTarget.Body = []byte(body)
vegetaTarget.Header.Set(libhttp.HeaderContentType, contentType)
}
}
}
return func(tgt *vegeta.Target) error {
if err != nil {
return fmt.Errorf(`DefaultHTTPAttack: %w`, err)
}
*tgt = vegetaTarget
return nil
}
}
}