18 Commits

Author SHA1 Message Date
7e05cf4f6b Merge pull request #101 from aykhans/feat/add-duration
All checks were successful
golangci-lint / lint (push) Successful in 23s
 Add duration
2025-03-24 18:12:10 +04:00
934cd0ad33 📚 Update docs 2025-03-24 17:02:58 +04:00
69c4841a05 📚 Update docs 2025-03-24 17:02:06 +04:00
3cc165cbf4 ⬆️ bump version to 0.6.2 2025-03-24 16:55:23 +04:00
59f40ad825 Add duration 2025-03-24 16:54:09 +04:00
a170588574 Merge pull request #100 from aykhans/refactor/config
All checks were successful
golangci-lint / lint (push) Successful in 25s
🔨 Add 'User-Agent' in 'SetDefaults' function
2025-03-23 21:19:31 +04:00
2a0ac390d8 🔨 Add 'User-Agent'in 'SetDefaults' function 2025-03-22 22:25:54 +04:00
11bb8b3fb0 Merge pull request #99 from aykhans/docs/update-readme
All checks were successful
golangci-lint / lint (push) Successful in 21s
📚 Update README.md
2025-03-20 19:23:41 +04:00
1aadc3419a 📚 Update README.md 2025-03-20 19:23:14 +04:00
b3af3f6ad5 Merge pull request #98 from aykhans/feat/config-yaml
All checks were successful
golangci-lint / lint (push) Successful in 1m15s
 Add yaml file reader to config
2025-03-20 16:38:13 +04:00
ed52fff363 ⬆️ bump version to 0.6.1 2025-03-20 16:31:39 +04:00
985fc6200d 🐳 Update Dockerfile 2025-03-20 16:11:43 +04:00
1808865358 📚 Update docs 2025-03-20 16:01:53 +04:00
56342e49c6 📚 Update docs 2025-03-20 15:59:46 +04:00
ec80569d5d 🐳 Remove default config file path from 'ENTRYPOINT' 2025-03-20 15:59:09 +04:00
459f7ee0dc Add yaml file reader to config 2025-03-20 03:52:25 +04:00
3cd72855e5 Merge pull request #97 from aykhans/fix/nil-url
All checks were successful
golangci-lint / lint (push) Successful in 58s
🐛 Fix nil URL referance
2025-03-20 03:20:33 +04:00
b8011ce651 🐛 Fix nil URL referance 2025-03-20 03:19:28 +04:00
22 changed files with 664 additions and 217 deletions

View File

@ -7,13 +7,11 @@ RUN go mod download
COPY . . COPY . .
RUN go build -ldflags "-s -w" -o dodo RUN go build -ldflags "-s -w" -o dodo
RUN echo "{}" > config.json
FROM gcr.io/distroless/static-debian12:latest FROM gcr.io/distroless/static-debian12:latest
WORKDIR / WORKDIR /
COPY --from=builder /src/dodo /dodo COPY --from=builder /src/dodo /dodo
COPY --from=builder /src/config.json /config.json
ENTRYPOINT ["./dodo", "-f", "/config.json"] ENTRYPOINT ["./dodo"]

165
README.md
View File

@ -3,78 +3,77 @@
<img width="30%" height="30%" src="https://ftp.aykhans.me/web/client/pubshares/VzPtSHS7yPQT7ngoZzZSNU/browse?path=%2Fdodo.png"> <img width="30%" height="30%" src="https://ftp.aykhans.me/web/client/pubshares/VzPtSHS7yPQT7ngoZzZSNU/browse?path=%2Fdodo.png">
</p> </p>
## Table of Contents
- [Installation](#installation)
- [Using Docker (Recommended)](#using-docker-recommended)
- [Using Pre-built Binaries](#using-pre-built-binaries)
- [Building from Source](#building-from-source)
- [Usage](#usage)
- [1. CLI Usage](#1-cli-usage)
- [2. Config File Usage](#2-config-file-usage)
- [2.1 JSON Example](#21-json-example)
- [2.2 YAML/YML Example](#22-yamlyml-example)
- [3. CLI & Config File Combination](#3-cli--config-file-combination)
- [Config Parameters Reference](#config-parameters-reference)
## Installation ## Installation
### Using Docker (Recommended) ### Using Docker (Recommended)
Pull the Dodo image from Docker Hub: Pull the latest Dodo image from Docker Hub:
```sh ```sh
docker pull aykhans/dodo:latest docker pull aykhans/dodo:latest
``` ```
When using Dodo with Docker and a local config file, you must provide the config.json file as a volume to the Docker run command (not as the "-f config.json" argument): To use Dodo with Docker and a local config file, mount the config file as a volume and pass it as an argument:
```sh ```sh
docker run -v /path/to/config.json:/config.json aykhans/dodo docker run -v /path/to/config.json:/config.json aykhans/dodo -f /config.json
``` ```
If you're using Dodo with Docker and providing a config file via URL, you don't need to set a volume: If you're using a remote config file via URL, you don't need to mount a volume:
```sh ```sh
docker run aykhans/dodo -f https://raw.githubusercontent.com/aykhans/dodo/main/config.json docker run aykhans/dodo -f https://raw.githubusercontent.com/aykhans/dodo/main/config.yaml
``` ```
### Using Binary Files ### Using Pre-built Binaries
You can download pre-built binaries from the [releases](https://github.com/aykhans/dodo/releases) section. Download the latest binaries from the [releases](https://github.com/aykhans/dodo/releases) section.
### Building from Source ### Building from Source
To build Dodo from source, you need to have [Go 1.24+](https://golang.org/dl/) installed. To build Dodo from source, ensure you have [Go 1.24+](https://golang.org/dl/) installed.
Follow these steps:
1. **Clone the repository:** ```sh
go install -ldflags "-s -w" github.com/aykhans/dodo@latest
```sh ```
git clone https://github.com/aykhans/dodo.git
```
2. **Navigate to the project directory:**
```sh
cd dodo
```
3. **Build the project:**
```sh
go build -ldflags "-s -w" -o dodo
```
This will generate an executable named `dodo` in the project directory.
## Usage ## Usage
You can use Dodo with CLI arguments, a JSON config file, or both. When using both, CLI arguments will override JSON config values if there's a conflict. Dodo supports CLI arguments, configuration files (JSON/YAML), or a combination of both. If both are used, CLI arguments take precedence.
### 1. CLI ### 1. CLI Usage
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 2 seconds: Send 1000 GET requests to https://example.com with 10 parallel dodos (threads), each with a timeout of 2 seconds, within a maximum duration of 1 minute:
```sh ```sh
dodo -u https://example.com -m GET -d 10 -r 1000 -t 2s dodo -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 2s
``` ```
With Docker: With Docker:
```sh ```sh
docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2s docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 2s
``` ```
### 2. JSON Config File ### 2. Config File Usage
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 800 milliseconds: Send 1000 GET requests to https://example.com with 10 parallel dodos (threads), each with a timeout of 800 milliseconds, within a maximum duration of 250 seconds:
#### 2.1 JSON Example
```jsonc ```jsonc
{ {
@ -84,6 +83,7 @@ Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) a
"timeout": "800ms", "timeout": "800ms",
"dodos": 10, "dodos": 10,
"requests": 1000, "requests": 1000,
"duration": "250s",
"params": [ "params": [
// A random value will be selected from the list for first "key1" param on each request // A random value will be selected from the list for first "key1" param on each request
@ -152,33 +152,110 @@ docker run --rm -i -v /path/to/config.json:/config.json aykhans/dodo
docker run --rm -i aykhans/dodo -f https://example.com/config.json docker run --rm -i aykhans/dodo -f https://example.com/config.json
``` ```
### 3. Combined (CLI & JSON) #### 2.2 YAML/YML Example
Override the config file arguments with CLI arguments: ```yaml
method: "GET"
url: "https://example.com"
yes: false
timeout: "800ms"
dodos: 10
requests: 1000
duration: "250s"
params:
# A random value will be selected from the list for first "key1" param on each request
# And always "value" for second "key1" param on each request
# e.g. "?key1=value2&key1=value"
- key1: ["value1", "value2", "value3", "value4"]
- key1: "value"
# A random value will be selected from the list for param "key2" on each request
# e.g. "?key2=value2"
- key2: ["value1", "value2"]
headers:
# A random value will be selected from the list for first "key1" header on each request
# And always "value" for second "key1" header on each request
# e.g. "key1: value3", "key1: value"
- key1: ["value1", "value2", "value3", "value4"]
- key1: "value"
# A random value will be selected from the list for header "key2" on each request
# e.g. "key2: value2"
- key2: ["value1", "value2"]
cookies:
# A random value will be selected from the list for first "key1" cookie on each request
# And always "value" for second "key1" cookie on each request
# e.g. "key1=value4; key1=value"
- key1: ["value1", "value2", "value3", "value4"]
- key1: "value"
# A random value will be selected from the list for cookie "key2" on each request
# e.g. "key2=value1"
- key2: ["value1", "value2"]
body: "body-text"
# OR
# A random body value will be selected from the list for each request
body:
- "body-text1"
- "body-text2"
- "body-text3"
proxy: "http://example.com:8080"
# OR
# A random proxy will be selected from the list for each request
proxy:
- "http://example.com:8080"
- "http://username:password@example.com:8080"
- "socks5://example.com:8080"
- "socks5h://example.com:8080"
```
```sh ```sh
dodo -f /path/to/config.json -u https://example.com -m GET -d 10 -r 1000 -t 5s dodo -f /path/config.yaml
# OR
dodo -f https://example.com/config.yaml
``` ```
With Docker: With Docker:
```sh ```sh
docker run --rm -i -v /path/to/config.json:/config.json aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 5s docker run --rm -i -v /path/to/config.yaml:/config.yaml aykhans/dodo -f /config.yaml
# OR
docker run --rm -i aykhans/dodo -f https://example.com/config.yaml
``` ```
## CLI and JSON Config Parameters ### 3. CLI & Config File Combination
CLI arguments override config file values:
```sh
dodo -f /path/to/config.yaml -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 5s
```
With Docker:
```sh
docker run --rm -i -v /path/to/config.json:/config.json aykhans/dodo -f /config.json -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 5s
```
## Config Parameters Reference
If `Headers`, `Params`, `Cookies`, `Body`, or `Proxy` fields have multiple values, each request will choose a random value from the list. If `Headers`, `Params`, `Cookies`, `Body`, or `Proxy` fields have multiple values, each request will choose a random value from the list.
| Parameter | JSON config file | CLI Flag | CLI Short Flag | Type | Description | Default | | Parameter | config file | CLI Flag | CLI Short Flag | Type | Description | Default |
| --------------- | ---------------- | ------------ | -------------- | ------------------------------ | --------------------------------------------------------------- | ------- | | --------------- | ----------- | ------------ | -------------- | ------------------------------ | ----------------------------------------------------------- | ------- |
| Config file | - | -config-file | -f | String | Path to local config file or http(s) URL of the config file | - | | Config file | - | -config-file | -f | String | Path to local config file or http(s) URL of the config file | - |
| Yes | yes | -yes | -y | Boolean | Answer yes to all questions | false | | Yes | yes | -yes | -y | Boolean | Answer yes to all questions | false |
| URL | url | -url | -u | String | URL to send the request to | - | | URL | url | -url | -u | String | URL to send the request to | - |
| Method | method | -method | -m | String | HTTP method | GET | | Method | method | -method | -m | String | HTTP method | GET |
| Requests | requests | -requests | -r | UnsignedInteger | Total number of requests to send | 1000 |
| Dodos (Threads) | dodos | -dodos | -d | UnsignedInteger | Number of dodos (threads) to send requests in parallel | 1 | | Dodos (Threads) | dodos | -dodos | -d | UnsignedInteger | Number of dodos (threads) to send requests in parallel | 1 |
| Timeout | timeout | -timeout | -t | Duration | Timeout for canceling each request | 10s | | Requests | requests | -requests | -r | UnsignedInteger | Total number of requests to send | - |
| Duration | duration | -duration | -o | Time | Maximum duration for the test | - |
| Timeout | timeout | -timeout | -t | Time | Timeout for canceling each request | 10s |
| Params | params | -param | -p | [{String: String OR [String]}] | Request parameters | - | | Params | params | -param | -p | [{String: String OR [String]}] | Request parameters | - |
| Headers | headers | -header | -H | [{String: String OR [String]}] | Request headers | - | | Headers | headers | -header | -H | [{String: String OR [String]}] | Request headers | - |
| Cookies | cookies | -cookie | -c | [{String: String OR [String]}] | Request cookies | - | | Cookies | cookies | -cookie | -c | [{String: String OR [String]}] | Request cookies | - |

View File

@ -5,6 +5,7 @@
"timeout": "5s", "timeout": "5s",
"dodos": 8, "dodos": 8,
"requests": 1000, "requests": 1000,
"duration": "10s",
"params": [ "params": [
{ "key1": ["value1", "value2", "value3", "value4"] }, { "key1": ["value1", "value2", "value3", "value4"] },

View File

@ -1,12 +1,10 @@
# YAML/YML config file option is not implemented yet.
# This file is a example for future implementation.
method: "GET" method: "GET"
url: "https://example.com" url: "https://example.com"
yes: false yes: false
timeout: "5s" timeout: "5s"
dodos: 10 dodos: 8
requests: 1000 requests: 1000
duration: "10s"
params: params:
- key1: ["value1", "value2", "value3", "value4"] - key1: ["value1", "value2", "value3", "value4"]
@ -25,6 +23,7 @@ cookies:
# body: "body-text" # body: "body-text"
# OR # OR
# A random body value will be selected from the list for each request
body: body:
- "body-text1" - "body-text1"
- "body-text2" - "body-text2"
@ -32,6 +31,7 @@ body:
# proxy: "http://example.com:8080" # proxy: "http://example.com:8080"
# OR # OR
# A random proxy will be selected from the list for each request
proxy: proxy:
- "http://example.com:8080" - "http://example.com:8080"
- "http://username:password@example.com:8080" - "http://username:password@example.com:8080"

View File

@ -16,8 +16,8 @@ const cliUsageText = `Usage:
Examples: Examples:
Simple usage only with URL: Simple usage:
dodo -u https://example.com dodo -u https://example.com -o 1m
Usage with config file: Usage with config file:
dodo -f /path/to/config/file/config.json dodo -f /path/to/config/file/config.json
@ -25,7 +25,7 @@ Usage with config file:
Usage with all flags: Usage with all flags:
dodo -f /path/to/config/file/config.json \ dodo -f /path/to/config/file/config.json \
-u https://example.com -m POST \ -u https://example.com -m POST \
-d 10 -r 1000 -t 3s \ -d 10 -r 1000 -o 3m -t 3s \
-b "body1" -body "body2" \ -b "body1" -body "body2" \
-H "header1:value1" -header "header2:value2" \ -H "header1:value1" -header "header2:value2" \
-p "param1=value1" -param "param2=value2" \ -p "param1=value1" -param "param2=value2" \
@ -39,13 +39,14 @@ Flags:
-y, -yes bool Answer yes to all questions (default %v) -y, -yes bool Answer yes to all questions (default %v)
-f, -config-file string Path to the local config file or http(s) URL of the config file -f, -config-file string Path to the local config file or http(s) URL of the config file
-d, -dodos uint Number of dodos(threads) (default %d) -d, -dodos uint Number of dodos(threads) (default %d)
-r, -requests uint Number of total requests (default %d) -r, -requests uint Number of total requests
-t, -timeout Duration Timeout for each request (e.g. 400ms, 15s, 1m10s) (default %v) -o, -duration Time Maximum duration for the test (e.g. 30s, 1m, 5h)
-t, -timeout Time Timeout for each request (e.g. 400ms, 15s, 1m10s) (default %v)
-u, -url string URL for stress testing -u, -url string URL for stress testing
-m, -method string HTTP Method for the request (default %s) -m, -method string HTTP Method for the request (default %s)
-b, -body [string] Body for the request (e.g. "body text") -b, -body [string] Body for the request (e.g. "body text")
-p, -param [string] Parameter for the request (e.g. "key1=value1") -p, -param [string] Parameter for the request (e.g. "key1=value1")
-H, -header [string] Header for the request (e.g. "key1: value1") -H, -header [string] Header for the request (e.g. "key1:value1")
-c, -cookie [string] Cookie for the request (e.g. "key1=value1") -c, -cookie [string] Cookie for the request (e.g. "key1=value1")
-x, -proxy [string] Proxy for the request (e.g. "http://proxy.example.com:8080")` -x, -proxy [string] Proxy for the request (e.g. "http://proxy.example.com:8080")`
@ -55,7 +56,6 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
cliUsageText+"\n", cliUsageText+"\n",
DefaultYes, DefaultYes,
DefaultDodosCount, DefaultDodosCount,
DefaultRequestCount,
DefaultTimeout, DefaultTimeout,
DefaultMethod, DefaultMethod,
) )
@ -70,6 +70,7 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
dodosCount = uint(0) dodosCount = uint(0)
requestCount = uint(0) requestCount = uint(0)
timeout time.Duration timeout time.Duration
duration time.Duration
) )
{ {
@ -94,6 +95,9 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
flag.UintVar(&requestCount, "requests", 0, "Number of total requests") flag.UintVar(&requestCount, "requests", 0, "Number of total requests")
flag.UintVar(&requestCount, "r", 0, "Number of total requests") flag.UintVar(&requestCount, "r", 0, "Number of total requests")
flag.DurationVar(&duration, "duration", 0, "Maximum duration of the test")
flag.DurationVar(&duration, "o", 0, "Maximum duration of the test")
flag.DurationVar(&timeout, "timeout", 0, "Timeout for each request (e.g. 400ms, 15s, 1m10s)") flag.DurationVar(&timeout, "timeout", 0, "Timeout for each request (e.g. 400ms, 15s, 1m10s)")
flag.DurationVar(&timeout, "t", 0, "Timeout for each request (e.g. 400ms, 15s, 1m10s)") flag.DurationVar(&timeout, "t", 0, "Timeout for each request (e.g. 400ms, 15s, 1m10s)")
@ -139,6 +143,8 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
config.DodosCount = utils.ToPtr(dodosCount) config.DodosCount = utils.ToPtr(dodosCount)
case "requests", "r": case "requests", "r":
config.RequestCount = utils.ToPtr(requestCount) config.RequestCount = utils.ToPtr(requestCount)
case "duration", "o":
config.Duration = &types.Duration{Duration: duration}
case "timeout", "t": case "timeout", "t":
config.Timeout = &types.Timeout{Duration: timeout} config.Timeout = &types.Timeout{Duration: timeout}
case "yes", "y": case "yes", "y":

View File

@ -15,29 +15,31 @@ import (
) )
const ( const (
VERSION string = "0.6.0" VERSION string = "0.6.2"
DefaultUserAgent string = "Dodo/" + VERSION DefaultUserAgent string = "Dodo/" + VERSION
DefaultMethod string = "GET" DefaultMethod string = "GET"
DefaultTimeout time.Duration = time.Second * 10 DefaultTimeout time.Duration = time.Second * 10
DefaultDodosCount uint = 1 DefaultDodosCount uint = 1
DefaultRequestCount uint = 1 DefaultRequestCount uint = 0
DefaultDuration time.Duration = 0
DefaultYes bool = false DefaultYes bool = false
) )
var SupportedProxySchemes []string = []string{"http", "socks5", "socks5h"} var SupportedProxySchemes []string = []string{"http", "socks5", "socks5h"}
type RequestConfig struct { type RequestConfig struct {
Method string `json:"method"` Method string
URL url.URL `json:"url"` URL url.URL
Timeout time.Duration `json:"timeout"` Timeout time.Duration
DodosCount uint `json:"dodos"` DodosCount uint
RequestCount uint `json:"requests"` RequestCount uint
Yes bool `json:"yes"` Duration time.Duration
Params types.Params `json:"params"` Yes bool
Headers types.Headers `json:"headers"` Params types.Params
Cookies types.Cookies `json:"cookies"` Headers types.Headers
Body types.Body `json:"body"` Cookies types.Cookies
Proxies types.Proxies `json:"proxies"` Body types.Body
Proxies types.Proxies
} }
func NewRequestConfig(conf *Config) *RequestConfig { func NewRequestConfig(conf *Config) *RequestConfig {
@ -47,6 +49,7 @@ func NewRequestConfig(conf *Config) *RequestConfig {
Timeout: conf.Timeout.Duration, Timeout: conf.Timeout.Duration,
DodosCount: *conf.DodosCount, DodosCount: *conf.DodosCount,
RequestCount: *conf.RequestCount, RequestCount: *conf.RequestCount,
Duration: conf.Duration.Duration,
Yes: *conf.Yes, Yes: *conf.Yes,
Params: conf.Params, Params: conf.Params,
Headers: conf.Headers, Headers: conf.Headers,
@ -57,6 +60,9 @@ func NewRequestConfig(conf *Config) *RequestConfig {
} }
func (rc *RequestConfig) GetValidDodosCountForRequests() uint { func (rc *RequestConfig) GetValidDodosCountForRequests() uint {
if rc.RequestCount == 0 {
return rc.DodosCount
}
return min(rc.DodosCount, rc.RequestCount) return min(rc.DodosCount, rc.RequestCount)
} }
@ -95,7 +101,17 @@ func (rc *RequestConfig) Print() {
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Dodos", rc.DodosCount}) t.AppendRow(table.Row{"Dodos", rc.DodosCount})
t.AppendSeparator() t.AppendSeparator()
if rc.RequestCount > 0 {
t.AppendRow(table.Row{"Requests", rc.RequestCount}) t.AppendRow(table.Row{"Requests", rc.RequestCount})
} else {
t.AppendRow(table.Row{"Requests"})
}
t.AppendSeparator()
if rc.Duration > 0 {
t.AppendRow(table.Row{"Duration", rc.Duration})
} else {
t.AppendRow(table.Row{"Duration"})
}
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Params", rc.Params.String()}) t.AppendRow(table.Row{"Params", rc.Params.String()})
t.AppendSeparator() t.AppendSeparator()
@ -111,17 +127,18 @@ func (rc *RequestConfig) Print() {
} }
type Config struct { type Config struct {
Method *string `json:"method"` Method *string `json:"method" yaml:"method"`
URL *types.RequestURL `json:"url"` URL *types.RequestURL `json:"url" yaml:"url"`
Timeout *types.Timeout `json:"timeout"` Timeout *types.Timeout `json:"timeout" yaml:"timeout"`
DodosCount *uint `json:"dodos"` DodosCount *uint `json:"dodos" yaml:"dodos"`
RequestCount *uint `json:"requests"` RequestCount *uint `json:"requests" yaml:"requests"`
Yes *bool `json:"yes"` Duration *types.Duration `json:"duration" yaml:"duration"`
Params types.Params `json:"params"` Yes *bool `json:"yes" yaml:"yes"`
Headers types.Headers `json:"headers"` Params types.Params `json:"params" yaml:"params"`
Cookies types.Cookies `json:"cookies"` Headers types.Headers `json:"headers" yaml:"headers"`
Body types.Body `json:"body"` Cookies types.Cookies `json:"cookies" yaml:"cookies"`
Proxies types.Proxies `json:"proxy"` Body types.Body `json:"body" yaml:"body"`
Proxies types.Proxies `json:"proxy" yaml:"proxy"`
} }
func NewConfig() *Config { func NewConfig() *Config {
@ -132,13 +149,14 @@ func (c *Config) Validate() []error {
var errs []error var errs []error
if utils.IsNilOrZero(c.URL) { if utils.IsNilOrZero(c.URL) {
errs = append(errs, errors.New("request URL is required")) errs = append(errs, errors.New("request URL is required"))
} } else {
if c.URL.Scheme == "" { if c.URL.Scheme == "" {
c.URL.Scheme = "http" c.URL.Scheme = "http"
} }
if c.URL.Scheme != "http" && c.URL.Scheme != "https" { if c.URL.Scheme != "http" && c.URL.Scheme != "https" {
errs = append(errs, errors.New("request URL scheme must be http or https")) errs = append(errs, errors.New("request URL scheme must be http or https"))
} }
urlParams := types.Params{} urlParams := types.Params{}
for key, values := range c.URL.Query() { for key, values := range c.URL.Query() {
for _, value := range values { for _, value := range values {
@ -150,6 +168,7 @@ func (c *Config) Validate() []error {
} }
c.Params = append(urlParams, c.Params...) c.Params = append(urlParams, c.Params...)
c.URL.RawQuery = "" c.URL.RawQuery = ""
}
if utils.IsNilOrZero(c.Method) { if utils.IsNilOrZero(c.Method) {
errs = append(errs, errors.New("request method is required")) errs = append(errs, errors.New("request method is required"))
@ -160,8 +179,8 @@ func (c *Config) Validate() []error {
if utils.IsNilOrZero(c.DodosCount) { if utils.IsNilOrZero(c.DodosCount) {
errs = append(errs, errors.New("dodos count must be greater than 0")) errs = append(errs, errors.New("dodos count must be greater than 0"))
} }
if utils.IsNilOrZero(c.RequestCount) { if utils.IsNilOrZero(c.Duration) && utils.IsNilOrZero(c.RequestCount) {
errs = append(errs, errors.New("request count must be greater than 0")) errs = append(errs, errors.New("you should provide at least one of duration or request count"))
} }
for i, proxy := range c.Proxies { for i, proxy := range c.Proxies {
@ -195,6 +214,9 @@ func (config *Config) MergeConfig(newConfig *Config) {
if newConfig.RequestCount != nil { if newConfig.RequestCount != nil {
config.RequestCount = newConfig.RequestCount config.RequestCount = newConfig.RequestCount
} }
if newConfig.Duration != nil {
config.Duration = newConfig.Duration
}
if newConfig.Yes != nil { if newConfig.Yes != nil {
config.Yes = newConfig.Yes config.Yes = newConfig.Yes
} }
@ -228,7 +250,11 @@ func (config *Config) SetDefaults() {
if config.RequestCount == nil { if config.RequestCount == nil {
config.RequestCount = utils.ToPtr(DefaultRequestCount) config.RequestCount = utils.ToPtr(DefaultRequestCount)
} }
if config.Duration == nil {
config.Duration = &types.Duration{Duration: DefaultDuration}
}
if config.Yes == nil { if config.Yes == nil {
config.Yes = utils.ToPtr(DefaultYes) config.Yes = utils.ToPtr(DefaultYes)
} }
config.Headers.SetIfNotExists("User-Agent", DefaultUserAgent)
} }

View File

@ -7,17 +7,24 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"slices"
"strings"
"time" "time"
"github.com/aykhans/dodo/types" "github.com/aykhans/dodo/types"
"gopkg.in/yaml.v3"
) )
var supportedFileTypes = []string{"json", "yaml", "yml"}
func (config *Config) ReadFile(filePath types.ConfigFile) error { func (config *Config) ReadFile(filePath types.ConfigFile) error {
var ( var (
data []byte data []byte
err error err error
) )
fileExt := filePath.Extension()
if slices.Contains(supportedFileTypes, fileExt) {
if filePath.LocationType() == types.FileLocationTypeRemoteHTTP { if filePath.LocationType() == types.FileLocationTypeRemoteHTTP {
client := &http.Client{ client := &http.Client{
Timeout: 10 * time.Second, Timeout: 10 * time.Second,
@ -40,7 +47,14 @@ func (config *Config) ReadFile(filePath types.ConfigFile) error {
} }
} }
if fileExt == "json" {
return parseJSONConfig(data, config) return parseJSONConfig(data, config)
} else if fileExt == "yml" || fileExt == "yaml" {
return parseYAMLConfig(data, config)
}
}
return fmt.Errorf("unsupported config file type (supported types: %v)", strings.Join(supportedFileTypes, ", "))
} }
func parseJSONConfig(data []byte, config *Config) error { func parseJSONConfig(data []byte, config *Config) error {
@ -58,3 +72,12 @@ func parseJSONConfig(data []byte, config *Config) error {
return nil return nil
} }
func parseYAMLConfig(data []byte, config *Config) error {
err := yaml.Unmarshal(data, &config)
if err != nil {
return fmt.Errorf("YAML Config file: %s", err.Error())
}
return nil
}

1
go.mod
View File

@ -5,6 +5,7 @@ go 1.24.0
require ( require (
github.com/jedib0t/go-pretty/v6 v6.6.7 github.com/jedib0t/go-pretty/v6 v6.6.7
github.com/valyala/fasthttp v1.59.0 github.com/valyala/fasthttp v1.59.0
gopkg.in/yaml.v3 v3.0.1
) )
require ( require (

2
go.sum
View File

@ -29,5 +29,7 @@ golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -7,6 +7,7 @@ import (
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
"time"
"github.com/aykhans/dodo/config" "github.com/aykhans/dodo/config"
"github.com/aykhans/dodo/requests" "github.com/aykhans/dodo/requests"
@ -49,6 +50,10 @@ func main() {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
go listenForTermination(func() { cancel() }) go listenForTermination(func() { cancel() })
if requestConf.Duration > 0 {
time.AfterFunc(requestConf.Duration, func() { cancel() })
}
responses, err := requests.Run(ctx, requestConf) responses, err := requests.Run(ctx, requestConf)
if err != nil { if err != nil {
if err == types.ErrInterrupt { if err == types.ErrInterrupt {

View File

@ -17,7 +17,7 @@ import (
func streamProgress( func streamProgress(
ctx context.Context, ctx context.Context,
wg *sync.WaitGroup, wg *sync.WaitGroup,
total int64, total uint,
message string, message string,
increase <-chan int64, increase <-chan int64,
) { ) {
@ -27,21 +27,26 @@ func streamProgress(
pw.SetStyle(progress.StyleBlocks) pw.SetStyle(progress.StyleBlocks)
pw.SetTrackerLength(40) pw.SetTrackerLength(40)
pw.SetUpdateFrequency(time.Millisecond * 250) pw.SetUpdateFrequency(time.Millisecond * 250)
if total == 0 {
pw.Style().Visibility.Percentage = false
}
go pw.Render() go pw.Render()
dodosTracker := progress.Tracker{ dodosTracker := progress.Tracker{
Message: message, Message: message,
Total: total, Total: int64(total),
} }
pw.AppendTracker(&dodosTracker) pw.AppendTracker(&dodosTracker)
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
if ctx.Err() != context.Canceled { if err := ctx.Err(); err == context.Canceled || err == context.DeadlineExceeded {
dodosTracker.MarkAsDone()
} else {
dodosTracker.MarkAsErrored() dodosTracker.MarkAsErrored()
} }
time.Sleep(time.Millisecond * 300)
fmt.Printf("\r") fmt.Printf("\r")
time.Sleep(time.Millisecond * 500)
pw.Stop()
return return
case value := <-increase: case value := <-increase:

View File

@ -166,9 +166,6 @@ func setRequestHeaders(req *fasthttp.Request, headers []types.KeyValue[string, s
for _, header := range headers { for _, header := range headers {
req.Header.Add(header.Key, header.Value) req.Header.Add(header.Key, header.Value)
} }
if req.Header.UserAgent() == nil {
req.Header.SetUserAgent(config.DefaultUserAgent)
}
} }
// setRequestCookies adds the cookies of the given request with the provided key-value pairs. // setRequestCookies adds the cookies of the given request with the provided key-value pairs.

View File

@ -59,17 +59,28 @@ func releaseDodos(
streamWG sync.WaitGroup streamWG sync.WaitGroup
requestCountPerDodo uint requestCountPerDodo uint
dodosCount uint = requestConfig.GetValidDodosCountForRequests() dodosCount uint = requestConfig.GetValidDodosCountForRequests()
dodosCountInt int = int(dodosCount)
responses = make([][]*Response, dodosCount) responses = make([][]*Response, dodosCount)
increase = make(chan int64, requestConfig.RequestCount) increase = make(chan int64, requestConfig.RequestCount)
) )
wg.Add(dodosCountInt) wg.Add(int(dodosCount))
streamWG.Add(1) streamWG.Add(1)
streamCtx, streamCtxCancel := context.WithCancel(context.Background()) streamCtx, streamCtxCancel := context.WithCancel(context.Background())
go streamProgress(streamCtx, &streamWG, int64(requestConfig.RequestCount), "Dodos Working🔥", increase) go streamProgress(streamCtx, &streamWG, requestConfig.RequestCount, "Dodos Working🔥", increase)
if requestConfig.RequestCount == 0 {
for i := range dodosCount {
go sendRequest(
ctx,
newRequest(*requestConfig, clients, int64(i)),
requestConfig.Timeout,
&responses[i],
increase,
&wg,
)
}
} else {
for i := range dodosCount { for i := range dodosCount {
if i+1 == dodosCount { if i+1 == dodosCount {
requestCountPerDodo = requestConfig.RequestCount - (i * requestConfig.RequestCount / dodosCount) requestCountPerDodo = requestConfig.RequestCount - (i * requestConfig.RequestCount / dodosCount)
@ -78,7 +89,7 @@ func releaseDodos(
(i * requestConfig.RequestCount / dodosCount) (i * requestConfig.RequestCount / dodosCount)
} }
go sendRequest( go sendRequestByCount(
ctx, ctx,
newRequest(*requestConfig, clients, int64(i)), newRequest(*requestConfig, clients, int64(i)),
requestConfig.Timeout, requestConfig.Timeout,
@ -88,17 +99,19 @@ func releaseDodos(
&wg, &wg,
) )
} }
}
wg.Wait() wg.Wait()
streamCtxCancel() streamCtxCancel()
streamWG.Wait() streamWG.Wait()
return utils.Flatten(responses) return utils.Flatten(responses)
} }
// sendRequest sends a specified number of HTTP requests concurrently with a given timeout. // sendRequestByCount sends a specified number of HTTP requests concurrently with a given timeout.
// It appends the responses to the provided responseData slice and sends the count of completed requests // It appends the responses to the provided responseData slice and sends the count of completed requests
// to the increase channel. The function terminates early if the context is canceled or if a custom // to the increase channel. The function terminates early if the context is canceled or if a custom
// interrupt error is encountered. // interrupt error is encountered.
func sendRequest( func sendRequestByCount(
ctx context.Context, ctx context.Context,
request *Request, request *Request,
timeout time.Duration, timeout time.Duration,
@ -142,3 +155,50 @@ func sendRequest(
}() }()
} }
} }
// sendRequest continuously sends HTTP requests until the context is canceled.
// It records the response status code or error message along with the response time,
// and signals each completed request through the increase channel.
func sendRequest(
ctx context.Context,
request *Request,
timeout time.Duration,
responseData *[]*Response,
increase chan<- int64,
wg *sync.WaitGroup,
) {
defer wg.Done()
for {
if ctx.Err() != nil {
return
}
func() {
startTime := time.Now()
response, err := request.Send(ctx, timeout)
completedTime := time.Since(startTime)
if response != nil {
defer fasthttp.ReleaseResponse(response)
}
if err != nil {
if err == types.ErrInterrupt {
return
}
*responseData = append(*responseData, &Response{
Response: err.Error(),
Time: completedTime,
})
increase <- 1
return
}
*responseData = append(*responseData, &Response{
Response: strconv.Itoa(response.StatusCode()),
Time: completedTime,
})
increase <- 1
}()
}
}

View File

@ -66,6 +66,28 @@ func (body *Body) UnmarshalJSON(b []byte) error {
return nil return nil
} }
func (body *Body) UnmarshalYAML(unmarshal func(interface{}) error) error {
var data any
if err := unmarshal(&data); err != nil {
return err
}
switch v := data.(type) {
case string:
*body = []string{v}
case []any:
var slice []string
for _, item := range v {
slice = append(slice, fmt.Sprintf("%v", item))
}
*body = slice
default:
return fmt.Errorf("invalid type for Body: %T (should be string or []string)", v)
}
return nil
}
func (body *Body) Set(value string) error { func (body *Body) Set(value string) error {
*body = append(*body, value) *body = append(*body, value)
return nil return nil

View File

@ -11,13 +11,22 @@ const (
type ConfigFile string type ConfigFile string
func (config ConfigFile) String() string { func (configFile ConfigFile) String() string {
return string(config) return string(configFile)
} }
func (config ConfigFile) LocationType() FileLocationType { func (configFile ConfigFile) LocationType() FileLocationType {
if strings.HasPrefix(string(config), "http://") || strings.HasPrefix(string(config), "https://") { if strings.HasPrefix(string(configFile), "http://") || strings.HasPrefix(string(configFile), "https://") {
return FileLocationTypeRemoteHTTP return FileLocationTypeRemoteHTTP
} }
return FileLocationTypeLocal return FileLocationTypeLocal
} }
func (configFile ConfigFile) Extension() string {
i := strings.LastIndex(configFile.String(), ".")
if i == -1 {
return ""
}
return configFile.String()[i+1:]
}

View File

@ -56,6 +56,23 @@ func (cookies Cookies) String() string {
return string(buffer.Bytes()) return string(buffer.Bytes())
} }
func (cookies *Cookies) AppendByKey(key, value string) {
if item := cookies.GetValue(key); item != nil {
*item = append(*item, value)
} else {
*cookies = append(*cookies, KeyValue[string, []string]{Key: key, Value: []string{value}})
}
}
func (cookies Cookies) GetValue(key string) *[]string {
for i := range cookies {
if cookies[i].Key == key {
return &cookies[i].Value
}
}
return nil
}
func (cookies *Cookies) UnmarshalJSON(b []byte) error { func (cookies *Cookies) UnmarshalJSON(b []byte) error {
var data []map[string]any var data []map[string]any
if err := json.Unmarshal(b, &data); err != nil { if err := json.Unmarshal(b, &data); err != nil {
@ -82,6 +99,31 @@ func (cookies *Cookies) UnmarshalJSON(b []byte) error {
return nil return nil
} }
func (cookies *Cookies) UnmarshalYAML(unmarshal func(interface{}) error) error {
var raw []map[string]any
if err := unmarshal(&raw); err != nil {
return err
}
for _, param := range raw {
for key, value := range param {
switch parsed := value.(type) {
case string:
*cookies = append(*cookies, KeyValue[string, []string]{Key: key, Value: []string{parsed}})
case []any:
var values []string
for _, v := range parsed {
if str, ok := v.(string); ok {
values = append(values, str)
}
}
*cookies = append(*cookies, KeyValue[string, []string]{Key: key, Value: values})
}
}
}
return nil
}
func (cookies *Cookies) Set(value string) error { func (cookies *Cookies) Set(value string) error {
parts := strings.SplitN(value, "=", 2) parts := strings.SplitN(value, "=", 2)
switch len(parts) { switch len(parts) {
@ -95,20 +137,3 @@ func (cookies *Cookies) Set(value string) error {
return nil return nil
} }
func (cookies *Cookies) AppendByKey(key, value string) {
if item := cookies.GetValue(key); item != nil {
*item = append(*item, value)
} else {
*cookies = append(*cookies, KeyValue[string, []string]{Key: key, Value: []string{value}})
}
}
func (cookies Cookies) GetValue(key string) *[]string {
for i := range cookies {
if cookies[i].Key == key {
return &cookies[i].Value
}
}
return nil
}

View File

@ -6,31 +6,52 @@ import (
"time" "time"
) )
type Timeout struct { type Duration struct {
time.Duration time.Duration
} }
func (timeout *Timeout) UnmarshalJSON(b []byte) error { func (duration *Duration) UnmarshalJSON(b []byte) error {
var v any var v any
if err := json.Unmarshal(b, &v); err != nil { if err := json.Unmarshal(b, &v); err != nil {
return err return err
} }
switch value := v.(type) { switch value := v.(type) {
case float64: case float64:
timeout.Duration = time.Duration(value) duration.Duration = time.Duration(value)
return nil return nil
case string: case string:
var err error var err error
timeout.Duration, err = time.ParseDuration(value) duration.Duration, err = time.ParseDuration(value)
if err != nil { if err != nil {
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)") return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)")
} }
return nil return nil
default: default:
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)") return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)")
} }
} }
func (timeout Timeout) MarshalJSON() ([]byte, error) { func (duration Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(timeout.Duration.String()) return json.Marshal(duration.Duration.String())
}
func (duration *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
var v any
if err := unmarshal(&v); err != nil {
return err
}
switch value := v.(type) {
case float64:
duration.Duration = time.Duration(value)
return nil
case string:
var err error
duration.Duration, err = time.ParseDuration(value)
if err != nil {
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)")
}
return nil
default:
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)")
}
} }

View File

@ -56,6 +56,32 @@ func (headers Headers) String() string {
return string(buffer.Bytes()) return string(buffer.Bytes())
} }
func (headers *Headers) AppendByKey(key, value string) {
if item := headers.GetValue(key); item != nil {
*item = append(*item, value)
} else {
*headers = append(*headers, KeyValue[string, []string]{Key: key, Value: []string{value}})
}
}
func (headers Headers) GetValue(key string) *[]string {
for i := range headers {
if headers[i].Key == key {
return &headers[i].Value
}
}
return nil
}
func (headers Headers) Has(key string) bool {
for i := range headers {
if headers[i].Key == key {
return true
}
}
return false
}
func (headers *Headers) UnmarshalJSON(b []byte) error { func (headers *Headers) UnmarshalJSON(b []byte) error {
var data []map[string]any var data []map[string]any
if err := json.Unmarshal(b, &data); err != nil { if err := json.Unmarshal(b, &data); err != nil {
@ -82,6 +108,31 @@ func (headers *Headers) UnmarshalJSON(b []byte) error {
return nil return nil
} }
func (headers *Headers) UnmarshalYAML(unmarshal func(interface{}) error) error {
var raw []map[string]any
if err := unmarshal(&raw); err != nil {
return err
}
for _, param := range raw {
for key, value := range param {
switch parsed := value.(type) {
case string:
*headers = append(*headers, KeyValue[string, []string]{Key: key, Value: []string{parsed}})
case []any:
var values []string
for _, v := range parsed {
if str, ok := v.(string); ok {
values = append(values, str)
}
}
*headers = append(*headers, KeyValue[string, []string]{Key: key, Value: values})
}
}
}
return nil
}
func (headers *Headers) Set(value string) error { func (headers *Headers) Set(value string) error {
parts := strings.SplitN(value, ":", 2) parts := strings.SplitN(value, ":", 2)
switch len(parts) { switch len(parts) {
@ -96,19 +147,10 @@ func (headers *Headers) Set(value string) error {
return nil return nil
} }
func (headers *Headers) AppendByKey(key, value string) { func (headers *Headers) SetIfNotExists(key string, value string) bool {
if item := headers.GetValue(key); item != nil { if headers.Has(key) {
*item = append(*item, value) return false
} else { }
*headers = append(*headers, KeyValue[string, []string]{Key: key, Value: []string{value}}) *headers = append(*headers, KeyValue[string, []string]{Key: key, Value: []string{value}})
} return true
}
func (headers Headers) GetValue(key string) *[]string {
for i := range headers {
if headers[i].Key == key {
return &headers[i].Value
}
}
return nil
} }

View File

@ -56,6 +56,23 @@ func (params Params) String() string {
return string(buffer.Bytes()) return string(buffer.Bytes())
} }
func (params *Params) AppendByKey(key, value string) {
if item := params.GetValue(key); item != nil {
*item = append(*item, value)
} else {
*params = append(*params, KeyValue[string, []string]{Key: key, Value: []string{value}})
}
}
func (params Params) GetValue(key string) *[]string {
for i := range params {
if params[i].Key == key {
return &params[i].Value
}
}
return nil
}
func (params *Params) UnmarshalJSON(b []byte) error { func (params *Params) UnmarshalJSON(b []byte) error {
var data []map[string]any var data []map[string]any
if err := json.Unmarshal(b, &data); err != nil { if err := json.Unmarshal(b, &data); err != nil {
@ -82,6 +99,31 @@ func (params *Params) UnmarshalJSON(b []byte) error {
return nil return nil
} }
func (params *Params) UnmarshalYAML(unmarshal func(interface{}) error) error {
var raw []map[string]any
if err := unmarshal(&raw); err != nil {
return err
}
for _, param := range raw {
for key, value := range param {
switch parsed := value.(type) {
case string:
*params = append(*params, KeyValue[string, []string]{Key: key, Value: []string{parsed}})
case []any:
var values []string
for _, v := range parsed {
if str, ok := v.(string); ok {
values = append(values, str)
}
}
*params = append(*params, KeyValue[string, []string]{Key: key, Value: values})
}
}
}
return nil
}
func (params *Params) Set(value string) error { func (params *Params) Set(value string) error {
parts := strings.SplitN(value, "=", 2) parts := strings.SplitN(value, "=", 2)
switch len(parts) { switch len(parts) {
@ -95,20 +137,3 @@ func (params *Params) Set(value string) error {
return nil return nil
} }
func (params *Params) AppendByKey(key, value string) {
if item := params.GetValue(key); item != nil {
*item = append(*item, value)
} else {
*params = append(*params, KeyValue[string, []string]{Key: key, Value: []string{value}})
}
}
func (params Params) GetValue(key string) *[]string {
for i := range params {
if params[i].Key == key {
return &params[i].Value
}
}
return nil
}

View File

@ -75,6 +75,36 @@ func (proxies *Proxies) UnmarshalJSON(b []byte) error {
return nil return nil
} }
func (proxies *Proxies) UnmarshalYAML(unmarshal func(interface{}) error) error {
var data any
if err := unmarshal(&data); err != nil {
return err
}
switch v := data.(type) {
case string:
parsed, err := url.Parse(v)
if err != nil {
return err
}
*proxies = []url.URL{*parsed}
case []any:
var urls []url.URL
for _, item := range v {
url, err := url.Parse(item.(string))
if err != nil {
return err
}
urls = append(urls, *url)
}
*proxies = urls
default:
return fmt.Errorf("invalid type for Body: %T (should be URL or []URL)", v)
}
return nil
}
func (proxies *Proxies) Set(value string) error { func (proxies *Proxies) Set(value string) error {
parsedURL, err := url.Parse(value) parsedURL, err := url.Parse(value)
if err != nil { if err != nil {

View File

@ -25,6 +25,21 @@ func (requestURL *RequestURL) UnmarshalJSON(data []byte) error {
return nil return nil
} }
func (requestURL *RequestURL) UnmarshalYAML(unmarshal func(interface{}) error) error {
var urlStr string
if err := unmarshal(&urlStr); err != nil {
return err
}
parsedURL, err := url.Parse(urlStr)
if err != nil {
return errors.New("Request URL is invalid")
}
requestURL.URL = *parsedURL
return nil
}
func (requestURL RequestURL) MarshalJSON() ([]byte, error) { func (requestURL RequestURL) MarshalJSON() ([]byte, error) {
return json.Marshal(requestURL.URL.String()) return json.Marshal(requestURL.URL.String())
} }

57
types/timeout.go Normal file
View File

@ -0,0 +1,57 @@
package types
import (
"encoding/json"
"errors"
"time"
)
type Timeout struct {
time.Duration
}
func (timeout *Timeout) UnmarshalJSON(b []byte) error {
var v any
if err := json.Unmarshal(b, &v); err != nil {
return err
}
switch value := v.(type) {
case float64:
timeout.Duration = time.Duration(value)
return nil
case string:
var err error
timeout.Duration, err = time.ParseDuration(value)
if err != nil {
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
}
return nil
default:
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
}
}
func (timeout Timeout) MarshalJSON() ([]byte, error) {
return json.Marshal(timeout.Duration.String())
}
func (timeout *Timeout) UnmarshalYAML(unmarshal func(interface{}) error) error {
var v any
if err := unmarshal(&v); err != nil {
return err
}
switch value := v.(type) {
case float64:
timeout.Duration = time.Duration(value)
return nil
case string:
var err error
timeout.Duration, err = time.ParseDuration(value)
if err != nil {
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
}
return nil
default:
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
}
}