mirror of
https://github.com/aykhans/dodo.git
synced 2025-07-01 16:07:49 +00:00
Compare commits
82 Commits
Author | SHA1 | Date | |
---|---|---|---|
a9021bd1a4 | |||
48c2dc7935 | |||
4cb0540824 | |||
a01bf19986 | |||
74dcecc8b1 | |||
00afca7139 | |||
1589fefeb8 | |||
bbc43bbaac | |||
89fcf5f174 | |||
a58f734a55 | |||
efd5176ab9 | |||
f0adcaf328 | |||
6314cf7724 | |||
140e570b85 | |||
83c5788e54 | |||
ca74092615 | |||
004b10ea3c | |||
4c9ceb1c4b | |||
6f3df7c45b | |||
8cd495055d | |||
391a5bc6ec | |||
a69e248f8c | |||
2634ca110c | |||
b1612598c4 | |||
ba79304b04 | |||
015cb15053 | |||
3dc002188e | |||
769c04685a | |||
e43378a9a4 | |||
e29e4f1bc6 | |||
7d2168a014 | |||
ba53e6b7f7 | |||
58964e1098 | |||
d4bf7358ff | |||
779d5e9b18 | |||
6a79d0b1d7 | |||
1e53b8a7fb | |||
0a8dbec739 | |||
3762890914 | |||
ca6b3d4eb2 | |||
1ee06aacc3 | |||
3d5834a6a6 | |||
f1521cbb74 | |||
40f8a1cc37 | |||
8a3574cd48 | |||
5a2a4c47b2 | |||
ff09a3365e | |||
c83246abe4 | |||
efc4c62001 | |||
f567774e3a | |||
d2bd60e3ff | |||
0fe782c768 | |||
b9dd14a588 | |||
18b1c7dae3 | |||
77ddcf722a | |||
048cb68898 | |||
fd5e87ee68 | |||
61b9ce943b | |||
6fceb0094b | |||
186683fce5 | |||
04e5b5f3eb | |||
2bebf09adb | |||
ebacebff16 | |||
575ca2913a | |||
4686e26ede | |||
bd33b2c6a2 | |||
3068e0acae | |||
7a40bbbd3c | |||
43c0bd2138 | |||
fddeec1791 | |||
6f5fa1860c | |||
4480aed0f0 | |||
f5144ac4be | |||
4a1051e08c | |||
2371986909 | |||
e9af46084d | |||
cdaa63152f | |||
16791421c7 | |||
c90cfd8090 | |||
1aaea8e437 | |||
c44a0c978a | |||
1ace7be2b4 |
@ -4,6 +4,7 @@ binaries
|
|||||||
dodo
|
dodo
|
||||||
.git
|
.git
|
||||||
.gitignore
|
.gitignore
|
||||||
|
.golangci.yml
|
||||||
README.md
|
README.md
|
||||||
LICENSE
|
LICENSE
|
||||||
config.json
|
config.json
|
||||||
|
25
.github/workflows/golangci-lint.yml
vendored
Normal file
25
.github/workflows/golangci-lint.yml
vendored
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
name: golangci-lint
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
golangci:
|
||||||
|
name: lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: stable
|
||||||
|
- name: golangci-lint
|
||||||
|
uses: golangci/golangci-lint-action@v6
|
||||||
|
with:
|
||||||
|
version: v1.64
|
||||||
|
args: --timeout=10m --config=.golangci.yml
|
27
.golangci.yml
Normal file
27
.golangci.yml
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
run:
|
||||||
|
go: "1.24"
|
||||||
|
concurrency: 8
|
||||||
|
timeout: 10m
|
||||||
|
|
||||||
|
linters:
|
||||||
|
disable-all: true
|
||||||
|
enable:
|
||||||
|
- asasalint
|
||||||
|
- asciicheck
|
||||||
|
- gofmt
|
||||||
|
- goimports
|
||||||
|
- gomodguard
|
||||||
|
- goprintffuncname
|
||||||
|
- govet
|
||||||
|
- ineffassign
|
||||||
|
- misspell
|
||||||
|
- nakedret
|
||||||
|
- nolintlint
|
||||||
|
- prealloc
|
||||||
|
- prealloc
|
||||||
|
- reassign
|
||||||
|
- staticcheck
|
||||||
|
- typecheck
|
||||||
|
- unconvert
|
||||||
|
- unused
|
||||||
|
- whitespace
|
@ -1,4 +1,4 @@
|
|||||||
FROM golang:1.23.2-alpine AS builder
|
FROM golang:1.24-alpine AS builder
|
||||||
|
|
||||||
WORKDIR /dodo
|
WORKDIR /dodo
|
||||||
|
|
||||||
|
9
Makefile
Normal file
9
Makefile
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
lint:
|
||||||
|
golangci-lint run
|
||||||
|
|
||||||
|
build:
|
||||||
|
go build -ldflags "-s -w" -o "./dodo"
|
||||||
|
|
||||||
|
build-all:
|
||||||
|
rm -rf ./binaries
|
||||||
|
./build.sh
|
40
README.md
40
README.md
@ -49,23 +49,37 @@ dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
|||||||
```
|
```
|
||||||
With Docker:
|
With Docker:
|
||||||
```sh
|
```sh
|
||||||
docker run --rm aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. JSON config file
|
### 2. JSON config file
|
||||||
You can find an example config structure in the [config.json](https://github.com/aykhans/dodo/blob/main/config.json) file:
|
You can find an example config structure in the [config.json](https://github.com/aykhans/dodo/blob/main/config.json) file:
|
||||||
```json
|
```jsonc
|
||||||
{
|
{
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"url": "https://example.com",
|
"url": "https://example.com",
|
||||||
"no_proxy_check": false,
|
"no_proxy_check": false,
|
||||||
"timeout": 2000,
|
"timeout": 10000,
|
||||||
"dodos_count": 10,
|
"dodos": 1,
|
||||||
"request_count": 1000,
|
"requests": 1,
|
||||||
"params": {},
|
"params": {
|
||||||
"headers": {},
|
// Random param value will be selected from the param-key1 and param-key2 list for each request
|
||||||
"cookies": {},
|
"param-key1": ["param-value1", "param-value2", "param-value3"],
|
||||||
"body": [""],
|
"param-key2": ["param-value1", "param-value2", "param-value3"]
|
||||||
|
},
|
||||||
|
"headers": {
|
||||||
|
// Random header value will be selected from the header-key1 and header-key2 list for each request
|
||||||
|
"header-key1": ["header-value1", "header-value2", "header-value3"],
|
||||||
|
"header-key2": ["header-value2", "header-value2", "header-value3"]
|
||||||
|
},
|
||||||
|
"cookies": {
|
||||||
|
// Random cookie value will be selected from the cookie-key1 and cookie-key2 list for each request
|
||||||
|
"cookie-key1": ["cookie-value1", "cookie-value2", "cookie-value3"],
|
||||||
|
"cookie-key2": ["cookie-value2", "cookie-value2", "cookie-value3"]
|
||||||
|
},
|
||||||
|
// Random body value will be selected from the body list for each request
|
||||||
|
"body": ["body1", "body2", "body3"],
|
||||||
|
// Random proxy will be selected from the proxy list for each request
|
||||||
"proxies": [
|
"proxies": [
|
||||||
{
|
{
|
||||||
"url": "http://example.com:8080",
|
"url": "http://example.com:8080",
|
||||||
@ -85,7 +99,7 @@ dodo -c /path/config.json
|
|||||||
```
|
```
|
||||||
With Docker:
|
With Docker:
|
||||||
```sh
|
```sh
|
||||||
docker run --rm -v ./path/config.json:/dodo/config.json -i aykhans/dodo
|
docker run --rm -i -v ./path/config.json:/dodo/config.json aykhans/dodo
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. Both (CLI & JSON)
|
### 3. Both (CLI & JSON)
|
||||||
@ -96,7 +110,7 @@ dodo -c /path/config.json -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
|||||||
```
|
```
|
||||||
With Docker:
|
With Docker:
|
||||||
```sh
|
```sh
|
||||||
docker run --rm -v ./path/config.json:/dodo/config.json -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
docker run --rm -i -v ./path/config.json:/dodo/config.json aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
||||||
```
|
```
|
||||||
|
|
||||||
## CLI and JSON Config Parameters
|
## CLI and JSON Config Parameters
|
||||||
@ -108,8 +122,8 @@ If the Headers, Params, Cookies and Body fields have multiple values, each reque
|
|||||||
| Yes | - | --yes | -y | Boolean | Answer yes to all questions | false |
|
| 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 |
|
||||||
| Request count | request_count | --request-count | -r | Integer | Total number of requests to send | 1000 |
|
| Requests | requests | --requests | -r | Integer | Total number of requests to send | 1000 |
|
||||||
| Dodos count (Threads) | dodos_count | --dodos-count | -d | Integer | Number of dodos (threads) to send requests in parallel | 1 |
|
| Dodos (Threads) | dodos | --dodos | -d | Integer | Number of dodos (threads) to send requests in parallel | 1 |
|
||||||
| Timeout | timeout | --timeout | -t | Integer | Timeout for canceling each request (milliseconds) | 10000 |
|
| Timeout | timeout | --timeout | -t | Integer | Timeout for canceling each request (milliseconds) | 10000 |
|
||||||
| No Proxy Check | no_proxy_check | --no-proxy-check| - | Boolean | Disable proxy check | false |
|
| No Proxy Check | no_proxy_check | --no-proxy-check| - | Boolean | Disable proxy check | false |
|
||||||
| Params | params | - | - | Key-Value {String: [String]} | Request parameters | - |
|
| Params | params | - | - | Key-Value {String: [String]} | Request parameters | - |
|
||||||
|
23
config.json
23
config.json
@ -1,14 +1,23 @@
|
|||||||
{
|
{
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"url": "https://example.com",
|
"url": "https://example.com",
|
||||||
"no_proxy_check": true,
|
"no_proxy_check": false,
|
||||||
"timeout": 10000,
|
"timeout": 10000,
|
||||||
"dodos_count": 50,
|
"dodos": 1,
|
||||||
"request_count": 1000,
|
"requests": 1,
|
||||||
"params": {},
|
"params": {
|
||||||
"headers": {},
|
"param-key1": ["param-value1", "param-value2", "param-value3"],
|
||||||
"cookies": {},
|
"param-key2": ["param-value1", "param-value2", "param-value3"]
|
||||||
"body": [""],
|
},
|
||||||
|
"headers": {
|
||||||
|
"header-key1": ["header-value1", "header-value2", "header-value3"],
|
||||||
|
"header-key2": ["header-value2", "header-value2", "header-value3"]
|
||||||
|
},
|
||||||
|
"cookies": {
|
||||||
|
"cookie-key1": ["cookie-value1", "cookie-value2", "cookie-value3"],
|
||||||
|
"cookie-key2": ["cookie-value2", "cookie-value2", "cookie-value3"]
|
||||||
|
},
|
||||||
|
"body": ["body1", "body2", "body3"],
|
||||||
"proxies": [
|
"proxies": [
|
||||||
{
|
{
|
||||||
"url": "http://example.com:8080",
|
"url": "http://example.com:8080",
|
||||||
|
@ -1,23 +1,24 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
. "github.com/aykhans/dodo/types"
|
||||||
"github.com/aykhans/dodo/utils"
|
"github.com/aykhans/dodo/utils"
|
||||||
"github.com/jedib0t/go-pretty/v6/table"
|
"github.com/jedib0t/go-pretty/v6/table"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
VERSION string = "0.5.2"
|
VERSION string = "0.5.7"
|
||||||
DefaultUserAgent string = "Dodo/" + VERSION
|
DefaultUserAgent string = "Dodo/" + VERSION
|
||||||
ProxyCheckURL string = "https://www.google.com"
|
ProxyCheckURL string = "https://www.google.com"
|
||||||
DefaultMethod string = "GET"
|
DefaultMethod string = "GET"
|
||||||
DefaultTimeout uint32 = 10000 // Milliseconds (10 seconds)
|
DefaultTimeout uint32 = 10000 // Milliseconds (10 seconds)
|
||||||
DefaultDodosCount uint = 1
|
DefaultDodosCount uint = 1
|
||||||
DefaultRequestCount uint = 1000
|
DefaultRequestCount uint = 1
|
||||||
MaxDodosCountForProxies uint = 20 // Max dodos count for proxy check
|
MaxDodosCountForProxies uint = 20 // Max dodos count for proxy check
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -41,7 +42,18 @@ func (config *RequestConfig) Print() {
|
|||||||
t.SetOutputMirror(os.Stdout)
|
t.SetOutputMirror(os.Stdout)
|
||||||
t.SetStyle(table.StyleLight)
|
t.SetStyle(table.StyleLight)
|
||||||
t.SetColumnConfigs([]table.ColumnConfig{
|
t.SetColumnConfigs([]table.ColumnConfig{
|
||||||
{Number: 2, WidthMax: 50},
|
{
|
||||||
|
Number: 2,
|
||||||
|
WidthMaxEnforcer: func(col string, maxLen int) string {
|
||||||
|
lines := strings.Split(col, "\n")
|
||||||
|
for i, line := range lines {
|
||||||
|
if len(line) > maxLen {
|
||||||
|
lines[i] = line[:maxLen-3] + "..."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
},
|
||||||
|
WidthMax: 50},
|
||||||
})
|
})
|
||||||
|
|
||||||
newHeaders := make(map[string][]string)
|
newHeaders := make(map[string][]string)
|
||||||
@ -55,23 +67,23 @@ func (config *RequestConfig) Print() {
|
|||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"URL", config.URL})
|
t.AppendRow(table.Row{"URL", config.URL})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Timeout", fmt.Sprintf("%dms", config.Timeout/time.Millisecond)})
|
t.AppendRow(table.Row{"Timeout", config.Timeout})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Dodos", config.DodosCount})
|
t.AppendRow(table.Row{"Dodos", config.DodosCount})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Requests", config.RequestCount})
|
t.AppendRow(table.Row{"Requests", config.RequestCount})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Params", utils.MarshalJSON(config.Params, 3)})
|
t.AppendRow(table.Row{"Params", string(utils.PrettyJSONMarshal(config.Params, 3, "", " "))})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Headers", utils.MarshalJSON(newHeaders, 3)})
|
t.AppendRow(table.Row{"Headers", string(utils.PrettyJSONMarshal(newHeaders, 3, "", " "))})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Cookies", utils.MarshalJSON(config.Cookies, 3)})
|
t.AppendRow(table.Row{"Cookies", string(utils.PrettyJSONMarshal(config.Cookies, 3, "", " "))})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Proxies Count", len(config.Proxies)})
|
t.AppendRow(table.Row{"Proxies", string(utils.PrettyJSONMarshal(config.Proxies, 3, "", " "))})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Proxy Check", !config.NoProxyCheck})
|
t.AppendRow(table.Row{"Proxy Check", !config.NoProxyCheck})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Body", utils.MarshalJSON(config.Body, 3)})
|
t.AppendRow(table.Row{"Body", string(utils.PrettyJSONMarshal(config.Body, 3, "", " "))})
|
||||||
|
|
||||||
t.Render()
|
t.Render()
|
||||||
}
|
}
|
||||||
@ -86,7 +98,7 @@ func (config *RequestConfig) GetValidDodosCountForProxies() uint {
|
|||||||
|
|
||||||
func (config *RequestConfig) GetMaxConns(minConns uint) uint {
|
func (config *RequestConfig) GetMaxConns(minConns uint) uint {
|
||||||
maxConns := max(
|
maxConns := max(
|
||||||
minConns, uint(config.GetValidDodosCountForRequests()),
|
minConns, config.GetValidDodosCountForRequests(),
|
||||||
)
|
)
|
||||||
return ((maxConns * 50 / 100) + maxConns)
|
return ((maxConns * 50 / 100) + maxConns)
|
||||||
}
|
}
|
||||||
@ -95,9 +107,9 @@ type Config struct {
|
|||||||
Method string `json:"method" validate:"http_method"` // custom validations: http_method
|
Method string `json:"method" validate:"http_method"` // custom validations: http_method
|
||||||
URL string `json:"url" validate:"http_url,required"`
|
URL string `json:"url" validate:"http_url,required"`
|
||||||
Timeout uint32 `json:"timeout" validate:"gte=1,lte=100000"`
|
Timeout uint32 `json:"timeout" validate:"gte=1,lte=100000"`
|
||||||
DodosCount uint `json:"dodos_count" validate:"gte=1"`
|
DodosCount uint `json:"dodos" validate:"gte=1"`
|
||||||
RequestCount uint `json:"request_count" validation_name:"request-count" validate:"gte=1"`
|
RequestCount uint `json:"requests" validation_name:"request-count" validate:"gte=1"`
|
||||||
NoProxyCheck utils.Option[bool] `json:"no_proxy_check"`
|
NoProxyCheck Option[bool] `json:"no_proxy_check"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewConfig(
|
func NewConfig(
|
||||||
@ -105,10 +117,10 @@ func NewConfig(
|
|||||||
timeout uint32,
|
timeout uint32,
|
||||||
dodosCount uint,
|
dodosCount uint,
|
||||||
requestCount uint,
|
requestCount uint,
|
||||||
noProxyCheck utils.Option[bool],
|
noProxyCheck Option[bool],
|
||||||
) *Config {
|
) *Config {
|
||||||
if noProxyCheck == nil {
|
if noProxyCheck == nil {
|
||||||
noProxyCheck = utils.NewNoneOption[bool]()
|
noProxyCheck = NewNoneOption[bool]()
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Config{
|
return &Config{
|
||||||
@ -155,7 +167,7 @@ func (config *Config) SetDefaults() {
|
|||||||
config.RequestCount = DefaultRequestCount
|
config.RequestCount = DefaultRequestCount
|
||||||
}
|
}
|
||||||
if config.NoProxyCheck.IsNone() {
|
if config.NoProxyCheck.IsNone() {
|
||||||
config.NoProxyCheck = utils.NewOption(false)
|
config.NoProxyCheck = NewOption(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -208,13 +220,13 @@ func (config *JSONConfig) MergeConfigs(newConfig *JSONConfig) {
|
|||||||
|
|
||||||
type CLIConfig struct {
|
type CLIConfig struct {
|
||||||
*Config
|
*Config
|
||||||
Yes bool `json:"yes" validate:"omitempty"`
|
Yes Option[bool] `json:"yes" validate:"omitempty"`
|
||||||
ConfigFile string `validation_name:"config-file" validate:"omitempty,filepath"`
|
ConfigFile string `validation_name:"config-file" validate:"omitempty,filepath"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCLIConfig(
|
func NewCLIConfig(
|
||||||
config *Config,
|
config *Config,
|
||||||
yes bool,
|
yes Option[bool],
|
||||||
configFile string,
|
configFile string,
|
||||||
) *CLIConfig {
|
) *CLIConfig {
|
||||||
return &CLIConfig{
|
return &CLIConfig{
|
||||||
@ -227,4 +239,7 @@ func (config *CLIConfig) MergeConfigs(newConfig *CLIConfig) {
|
|||||||
if newConfig.ConfigFile != "" {
|
if newConfig.ConfigFile != "" {
|
||||||
config.ConfigFile = newConfig.ConfigFile
|
config.ConfigFile = newConfig.ConfigFile
|
||||||
}
|
}
|
||||||
|
if !newConfig.Yes.IsNone() {
|
||||||
|
config.Yes = newConfig.Yes
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -19,10 +19,6 @@ func OSErrorFormater(err error) error {
|
|||||||
return ErrInvalidFile
|
return ErrInvalidFile
|
||||||
}
|
}
|
||||||
|
|
||||||
func CobraErrorFormater(err error) error {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func shortenNamespace(namespace string) string {
|
func shortenNamespace(namespace string) string {
|
||||||
return namespace[strings.Index(namespace, ".")+1:]
|
return namespace[strings.Index(namespace, ".")+1:]
|
||||||
}
|
}
|
||||||
|
31
go.mod
31
go.mod
@ -1,29 +1,32 @@
|
|||||||
module github.com/aykhans/dodo
|
module github.com/aykhans/dodo
|
||||||
|
|
||||||
go 1.23.2
|
go 1.24
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/go-playground/validator/v10 v10.23.0
|
github.com/go-playground/validator/v10 v10.25.0
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.2
|
github.com/jedib0t/go-pretty/v6 v6.6.6
|
||||||
github.com/spf13/cobra v1.8.1
|
github.com/valyala/fasthttp v1.59.0
|
||||||
github.com/spf13/pflag v1.0.5
|
golang.org/x/net v0.35.0
|
||||||
github.com/valyala/fasthttp v1.57.0
|
)
|
||||||
golang.org/x/net v0.31.0
|
|
||||||
|
require (
|
||||||
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.4 // indirect
|
github.com/fatih/color v1.18.0
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
|
||||||
github.com/klauspost/compress v1.17.11 // indirect
|
github.com/klauspost/compress v1.17.11 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/mattn/go-runewidth v0.0.15 // indirect
|
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||||
github.com/rivo/uniseg v0.4.7 // indirect
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
golang.org/x/crypto v0.29.0 // indirect
|
golang.org/x/crypto v0.33.0 // indirect
|
||||||
golang.org/x/sys v0.27.0 // indirect
|
golang.org/x/sys v0.30.0 // indirect
|
||||||
golang.org/x/term v0.26.0 // indirect
|
golang.org/x/term v0.29.0 // indirect
|
||||||
golang.org/x/text v0.20.0 // indirect
|
golang.org/x/text v0.22.0 // indirect
|
||||||
)
|
)
|
||||||
|
62
go.sum
62
go.sum
@ -1,56 +1,56 @@
|
|||||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I=
|
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s=
|
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
||||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
github.com/go-playground/validator/v10 v10.23.0 h1:/PwmTwZhS0dPkav3cdK9kV1FsAmrL8sThn8IHr/sO+o=
|
github.com/go-playground/validator/v10 v10.25.0 h1:5Dh7cjvzR7BRZadnsVOzPhWsrwUr0nmsZJxEAnFLNO8=
|
||||||
github.com/go-playground/validator/v10 v10.23.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
github.com/go-playground/validator/v10 v10.25.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
github.com/jedib0t/go-pretty/v6 v6.6.6 h1:LyezkL+1SuqH2z47e5IMQkYUIcs2BD+MnpdPRiRcN0c=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
github.com/jedib0t/go-pretty/v6 v6.6.6/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.2 h1:27bLj3nRODzaiA7tPIxy9UVWHoPspFfME9XxgwiiNsM=
|
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.2/go.mod h1:zbn98qrYlh95FIhwwsbIip0LYpwSG8SUOScs+v9/t0E=
|
|
||||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||||
|
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
|
||||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
|
||||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
|
||||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
|
||||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
|
||||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
github.com/valyala/fasthttp v1.57.0 h1:Xw8SjWGEP/+wAAgyy5XTvgrWlOD1+TxbbvNADYCm1Tg=
|
github.com/valyala/fasthttp v1.59.0 h1:Qu0qYHfXvPk1mSLNqcFtEk6DpxgA26hy6bmydotDpRI=
|
||||||
github.com/valyala/fasthttp v1.57.0/go.mod h1:h6ZBaPRlzpZ6O3H5t2gEk1Qi33+TmLvfwgLLp0t9CpE=
|
github.com/valyala/fasthttp v1.59.0/go.mod h1:GTxNb9Bc6r2a9D0TWNSPwDz78UxnTGBViY3xZNEqyYU=
|
||||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||||
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
|
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
||||||
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
|
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||||
golang.org/x/net v0.31.0 h1:68CPQngjLL0r2AlUKiSxtQFKvzRVbnzLwMUn5SzcLHo=
|
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
||||||
golang.org/x/net v0.31.0/go.mod h1:P4fl1q7dY2hnZFxEk4pPSkDHF+QqjitcnDjUQyMM+pM=
|
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
||||||
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/term v0.26.0 h1:WEQa6V3Gja/BhNxg540hBip/kkaYtRg3cxg4oXSw4AU=
|
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||||
golang.org/x/term v0.26.0/go.mod h1:Si5m1o57C5nBNQo5z1iq+XDijt21BDBDp2bK0QI8e3E=
|
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
|
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
|
||||||
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||||
|
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||||
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=
|
||||||
|
17
main.go
17
main.go
@ -16,6 +16,7 @@ import (
|
|||||||
"github.com/aykhans/dodo/requests"
|
"github.com/aykhans/dodo/requests"
|
||||||
"github.com/aykhans/dodo/utils"
|
"github.com/aykhans/dodo/utils"
|
||||||
"github.com/aykhans/dodo/validation"
|
"github.com/aykhans/dodo/validation"
|
||||||
|
"github.com/fatih/color"
|
||||||
goValidator "github.com/go-playground/validator/v10"
|
goValidator "github.com/go-playground/validator/v10"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -27,9 +28,13 @@ func main() {
|
|||||||
)
|
)
|
||||||
|
|
||||||
cliConf, err := readers.CLIConfigReader()
|
cliConf, err := readers.CLIConfigReader()
|
||||||
if err != nil || cliConf == nil {
|
if err != nil {
|
||||||
|
utils.PrintAndExit(err.Error())
|
||||||
|
}
|
||||||
|
if cliConf == nil {
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := validator.StructPartial(cliConf, "ConfigFile"); err != nil {
|
if err := validator.StructPartial(cliConf, "ConfigFile"); err != nil {
|
||||||
utils.PrintErrAndExit(
|
utils.PrintErrAndExit(
|
||||||
customerrors.ValidationErrorsFormater(
|
customerrors.ValidationErrorsFormater(
|
||||||
@ -82,11 +87,11 @@ func main() {
|
|||||||
Cookies: jsonConf.Cookies,
|
Cookies: jsonConf.Cookies,
|
||||||
Proxies: jsonConf.Proxies,
|
Proxies: jsonConf.Proxies,
|
||||||
Body: jsonConf.Body,
|
Body: jsonConf.Body,
|
||||||
Yes: cliConf.Yes,
|
Yes: cliConf.Yes.ValueOr(false),
|
||||||
NoProxyCheck: conf.NoProxyCheck.ValueOrPanic(),
|
NoProxyCheck: conf.NoProxyCheck.ValueOr(false),
|
||||||
}
|
}
|
||||||
requestConf.Print()
|
requestConf.Print()
|
||||||
if !cliConf.Yes {
|
if !cliConf.Yes.ValueOr(false) {
|
||||||
response := readers.CLIYesOrNoReader("Do you want to continue?", true)
|
response := readers.CLIYesOrNoReader("Do you want to continue?", true)
|
||||||
if !response {
|
if !response {
|
||||||
utils.PrintAndExit("Exiting...")
|
utils.PrintAndExit("Exiting...")
|
||||||
@ -105,13 +110,13 @@ func main() {
|
|||||||
responses, err := requests.Run(ctx, requestConf)
|
responses, err := requests.Run(ctx, requestConf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if customerrors.Is(err, customerrors.ErrInterrupt) {
|
if customerrors.Is(err, customerrors.ErrInterrupt) {
|
||||||
utils.PrintlnC(utils.Colors.Yellow, err.Error())
|
color.Yellow(err.Error())
|
||||||
return
|
return
|
||||||
} else if customerrors.Is(err, customerrors.ErrNoInternet) {
|
} else if customerrors.Is(err, customerrors.ErrNoInternet) {
|
||||||
utils.PrintAndExit("No internet connection")
|
utils.PrintAndExit("No internet connection")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
panic(err)
|
utils.PrintErrAndExit(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
responses.Print()
|
responses.Print()
|
||||||
|
147
readers/cli.go
147
readers/cli.go
@ -1,69 +1,128 @@
|
|||||||
package readers
|
package readers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/aykhans/dodo/config"
|
"github.com/aykhans/dodo/config"
|
||||||
"github.com/aykhans/dodo/custom_errors"
|
. "github.com/aykhans/dodo/types"
|
||||||
"github.com/aykhans/dodo/utils"
|
"github.com/fatih/color"
|
||||||
"github.com/spf13/cobra"
|
|
||||||
"github.com/spf13/pflag"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func CLIConfigReader() (*config.CLIConfig, error) {
|
const usageText = `Usage:
|
||||||
var (
|
dodo [flags]
|
||||||
returnNil = false
|
|
||||||
cliConfig = config.NewCLIConfig(config.NewConfig("", 0, 0, 0, nil), false, "")
|
Examples:
|
||||||
dodosCount uint
|
|
||||||
requestCount uint
|
Simple usage only with URL:
|
||||||
timeout uint32
|
|
||||||
noProxyCheck bool
|
|
||||||
rootCmd = &cobra.Command{
|
|
||||||
Use: "dodo [flags]",
|
|
||||||
Example: ` Simple usage only with URL:
|
|
||||||
dodo -u https://example.com
|
dodo -u https://example.com
|
||||||
|
|
||||||
Simple usage with config file:
|
Simple usage with config file:
|
||||||
dodo -c /path/to/config/file/config.json
|
dodo -c /path/to/config/file/config.json
|
||||||
|
|
||||||
Usage with all flags:
|
Usage with all flags:
|
||||||
dodo -c /path/to/config/file/config.json -u https://example.com -m POST -d 10 -r 1000 -t 2000 --no-proxy-check -y`,
|
dodo -c /path/to/config/file/config.json -u https://example.com -m POST -d 10 -r 1000 -t 2000 --no-proxy-check -y
|
||||||
Run: func(cmd *cobra.Command, args []string) {},
|
|
||||||
SilenceErrors: true,
|
|
||||||
SilenceUsage: true,
|
|
||||||
Version: config.VERSION,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
rootCmd.Flags().StringVarP(&cliConfig.ConfigFile, "config-file", "c", "", "Path to the config file")
|
Flags:
|
||||||
rootCmd.Flags().BoolVarP(&cliConfig.Yes, "yes", "y", false, "Answer yes to all questions")
|
-h, --help help for dodo
|
||||||
rootCmd.Flags().StringVarP(&cliConfig.Method, "method", "m", "", fmt.Sprintf("HTTP Method (default %s)", config.DefaultMethod))
|
-v, --version version for dodo
|
||||||
rootCmd.Flags().StringVarP(&cliConfig.URL, "url", "u", "", "URL for stress testing")
|
-c, --config-file string Path to the config file
|
||||||
rootCmd.Flags().UintVarP(&dodosCount, "dodos-count", "d", config.DefaultDodosCount, "Number of dodos(threads)")
|
-d, --dodos uint Number of dodos(threads) (default %d)
|
||||||
rootCmd.Flags().UintVarP(&requestCount, "request-count", "r", config.DefaultRequestCount, "Number of total requests")
|
-m, --method string HTTP Method (default %s)
|
||||||
rootCmd.Flags().Uint32VarP(&timeout, "timeout", "t", config.DefaultTimeout, "Timeout for each request in milliseconds")
|
-r, --request uint Number of total requests (default %d)
|
||||||
rootCmd.Flags().BoolVar(&noProxyCheck, "no-proxy-check", false, "Do not check for proxies")
|
-t, --timeout uint32 Timeout for each request in milliseconds (default %d)
|
||||||
if err := rootCmd.Execute(); err != nil {
|
-u, --url string URL for stress testing
|
||||||
utils.PrintErr(err)
|
--no-proxy-check bool Do not check for proxies (default false)
|
||||||
rootCmd.Println(rootCmd.UsageString())
|
-y, --yes bool Answer yes to all questions (default false)`
|
||||||
return nil, customerrors.CobraErrorFormater(err)
|
|
||||||
|
func CLIConfigReader() (*config.CLIConfig, error) {
|
||||||
|
flag.Usage = func() {
|
||||||
|
fmt.Printf(
|
||||||
|
usageText+"\n",
|
||||||
|
config.DefaultDodosCount,
|
||||||
|
config.DefaultMethod,
|
||||||
|
config.DefaultRequestCount,
|
||||||
|
config.DefaultTimeout,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
rootCmd.Flags().Visit(func(f *pflag.Flag) {
|
|
||||||
|
var (
|
||||||
|
cliConfig = config.NewCLIConfig(config.NewConfig("", 0, 0, 0, nil), NewOption(false), "")
|
||||||
|
configFile = ""
|
||||||
|
yes = false
|
||||||
|
method = ""
|
||||||
|
url = ""
|
||||||
|
dodosCount uint = 0
|
||||||
|
requestsCount uint = 0
|
||||||
|
timeout uint = 0
|
||||||
|
noProxyCheck bool = false
|
||||||
|
)
|
||||||
|
{
|
||||||
|
flag.Bool("version", false, "Prints the version of the program")
|
||||||
|
flag.Bool("v", false, "Prints the version of the program")
|
||||||
|
|
||||||
|
flag.StringVar(&configFile, "config-file", "", "Path to the configuration file")
|
||||||
|
flag.StringVar(&configFile, "c", "", "Path to the configuration file")
|
||||||
|
|
||||||
|
flag.BoolVar(&yes, "yes", false, "Answer yes to all questions")
|
||||||
|
flag.BoolVar(&yes, "y", false, "Answer yes to all questions")
|
||||||
|
|
||||||
|
flag.StringVar(&method, "method", "", "HTTP Method")
|
||||||
|
flag.StringVar(&method, "m", "", "HTTP Method")
|
||||||
|
|
||||||
|
flag.StringVar(&url, "url", "", "URL to send the request")
|
||||||
|
flag.StringVar(&url, "u", "", "URL to send the request")
|
||||||
|
|
||||||
|
flag.UintVar(&dodosCount, "dodos", 0, "Number of dodos(threads)")
|
||||||
|
flag.UintVar(&dodosCount, "d", 0, "Number of dodos(threads)")
|
||||||
|
|
||||||
|
flag.UintVar(&requestsCount, "requests", 0, "Number of total requests")
|
||||||
|
flag.UintVar(&requestsCount, "r", 0, "Number of total requests")
|
||||||
|
|
||||||
|
flag.UintVar(&timeout, "timeout", 0, "Timeout for each request in milliseconds")
|
||||||
|
flag.UintVar(&timeout, "t", 0, "Timeout for each request in milliseconds")
|
||||||
|
|
||||||
|
flag.BoolVar(&noProxyCheck, "no-proxy-check", false, "Do not check for active proxies")
|
||||||
|
}
|
||||||
|
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
args := flag.Args()
|
||||||
|
if len(args) > 0 {
|
||||||
|
return nil, fmt.Errorf("unexpected arguments: %v", strings.Join(args, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
|
returnNil := false
|
||||||
|
flag.Visit(func(f *flag.Flag) {
|
||||||
switch f.Name {
|
switch f.Name {
|
||||||
case "help":
|
case "version", "v":
|
||||||
|
fmt.Printf("dodo version %s\n", config.VERSION)
|
||||||
returnNil = true
|
returnNil = true
|
||||||
case "version":
|
case "config-file", "c":
|
||||||
returnNil = true
|
cliConfig.ConfigFile = configFile
|
||||||
case "dodos-count":
|
case "yes", "y":
|
||||||
|
cliConfig.Yes.SetValue(yes)
|
||||||
|
case "method", "m":
|
||||||
|
cliConfig.Method = method
|
||||||
|
case "url", "u":
|
||||||
|
cliConfig.URL = url
|
||||||
|
case "dodos", "d":
|
||||||
cliConfig.DodosCount = dodosCount
|
cliConfig.DodosCount = dodosCount
|
||||||
case "request-count":
|
case "requests", "r":
|
||||||
cliConfig.RequestCount = requestCount
|
cliConfig.RequestCount = requestsCount
|
||||||
case "timeout":
|
case "timeout", "t":
|
||||||
cliConfig.Timeout = timeout
|
var maxUint32 uint = 4294967295
|
||||||
|
if timeout > maxUint32 {
|
||||||
|
color.Yellow("timeout value is too large, setting to %d", maxUint32)
|
||||||
|
timeout = maxUint32
|
||||||
|
}
|
||||||
|
cliConfig.Timeout = uint32(timeout)
|
||||||
case "no-proxy-check":
|
case "no-proxy-check":
|
||||||
cliConfig.NoProxyCheck = utils.NewOption(noProxyCheck)
|
cliConfig.NoProxyCheck.SetValue(noProxyCheck)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if returnNil {
|
if returnNil {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
@ -11,6 +11,7 @@ import (
|
|||||||
"github.com/aykhans/dodo/config"
|
"github.com/aykhans/dodo/config"
|
||||||
"github.com/aykhans/dodo/readers"
|
"github.com/aykhans/dodo/readers"
|
||||||
"github.com/aykhans/dodo/utils"
|
"github.com/aykhans/dodo/utils"
|
||||||
|
"github.com/fatih/color"
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
"github.com/valyala/fasthttp/fasthttpproxy"
|
"github.com/valyala/fasthttp/fasthttpproxy"
|
||||||
)
|
)
|
||||||
@ -73,18 +74,9 @@ func getClients(
|
|||||||
var yesOrNoDefault bool
|
var yesOrNoDefault bool
|
||||||
if activeProxyClientsCount == 0 {
|
if activeProxyClientsCount == 0 {
|
||||||
yesOrNoDefault = false
|
yesOrNoDefault = false
|
||||||
yesOrNoMessage = utils.Colored(
|
yesOrNoMessage = color.YellowString("No active proxies found. Do you want to continue?")
|
||||||
utils.Colors.Yellow,
|
|
||||||
"No active proxies found. Do you want to continue?",
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
yesOrNoMessage = utils.Colored(
|
yesOrNoMessage = color.YellowString("Found %d active proxies. Do you want to continue?", activeProxyClientsCount)
|
||||||
utils.Colors.Yellow,
|
|
||||||
fmt.Sprintf(
|
|
||||||
"Found %d active proxies. Do you want to continue?",
|
|
||||||
activeProxyClientsCount,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
if !yes {
|
if !yes {
|
||||||
response := readers.CLIYesOrNoReader("\n"+yesOrNoMessage, yesOrNoDefault)
|
response := readers.CLIYesOrNoReader("\n"+yesOrNoMessage, yesOrNoDefault)
|
||||||
|
@ -26,7 +26,6 @@ type Request struct {
|
|||||||
func (r *Request) Send(ctx context.Context, timeout time.Duration) (*fasthttp.Response, error) {
|
func (r *Request) Send(ctx context.Context, timeout time.Duration) (*fasthttp.Response, error) {
|
||||||
client := r.getClient()
|
client := r.getClient()
|
||||||
request := r.getRequest()
|
request := r.getRequest()
|
||||||
defer client.CloseIdleConnections()
|
|
||||||
defer fasthttp.ReleaseRequest(request)
|
defer fasthttp.ReleaseRequest(request)
|
||||||
|
|
||||||
response := fasthttp.AcquireResponse()
|
response := fasthttp.AcquireResponse()
|
||||||
|
@ -1,85 +1,108 @@
|
|||||||
package requests
|
package requests
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
. "github.com/aykhans/dodo/types"
|
||||||
"github.com/aykhans/dodo/utils"
|
"github.com/aykhans/dodo/utils"
|
||||||
"github.com/jedib0t/go-pretty/v6/table"
|
"github.com/jedib0t/go-pretty/v6/table"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Response struct {
|
type Response struct {
|
||||||
StatusCode int
|
Response string
|
||||||
Error error
|
|
||||||
Time time.Duration
|
Time time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
type Responses []*Response
|
type Responses []*Response
|
||||||
|
|
||||||
// Print prints the responses in a tabular format, including information such as
|
// Print prints the responses in a tabular format, including information such as
|
||||||
// response count, minimum time, maximum time, and average time.
|
// response count, minimum time, maximum time, average time, and latency percentiles.
|
||||||
func (respones Responses) Print() {
|
func (responses Responses) Print() {
|
||||||
var (
|
total := struct {
|
||||||
totalMinDuration time.Duration = respones[0].Time
|
Count int
|
||||||
totalMaxDuration time.Duration = respones[0].Time
|
Min time.Duration
|
||||||
totalDuration time.Duration
|
Max time.Duration
|
||||||
totalCount int = len(respones)
|
Sum time.Duration
|
||||||
)
|
P90 time.Duration
|
||||||
mergedResponses := make(map[string][]time.Duration)
|
P95 time.Duration
|
||||||
|
P99 time.Duration
|
||||||
for _, response := range respones {
|
}{
|
||||||
if response.Time < totalMinDuration {
|
Count: len(responses),
|
||||||
totalMinDuration = response.Time
|
Min: responses[0].Time,
|
||||||
|
Max: responses[0].Time,
|
||||||
}
|
}
|
||||||
if response.Time > totalMaxDuration {
|
mergedResponses := make(map[string]Durations)
|
||||||
totalMaxDuration = response.Time
|
var allDurations Durations
|
||||||
}
|
|
||||||
totalDuration += response.Time
|
|
||||||
|
|
||||||
if response.Error != nil {
|
for _, response := range responses {
|
||||||
mergedResponses[response.Error.Error()] = append(
|
if response.Time < total.Min {
|
||||||
mergedResponses[response.Error.Error()],
|
total.Min = response.Time
|
||||||
response.Time,
|
}
|
||||||
)
|
if response.Time > total.Max {
|
||||||
} else {
|
total.Max = response.Time
|
||||||
mergedResponses[fmt.Sprintf("%d", response.StatusCode)] = append(
|
}
|
||||||
mergedResponses[fmt.Sprintf("%d", response.StatusCode)],
|
total.Sum += response.Time
|
||||||
|
|
||||||
|
mergedResponses[response.Response] = append(
|
||||||
|
mergedResponses[response.Response],
|
||||||
response.Time,
|
response.Time,
|
||||||
)
|
)
|
||||||
|
allDurations = append(allDurations, response.Time)
|
||||||
}
|
}
|
||||||
}
|
allDurations.Sort()
|
||||||
|
allDurationsLenAsFloat := float64(len(allDurations) - 1)
|
||||||
|
total.P90 = allDurations[int(0.90*allDurationsLenAsFloat)]
|
||||||
|
total.P95 = allDurations[int(0.95*allDurationsLenAsFloat)]
|
||||||
|
total.P99 = allDurations[int(0.99*allDurationsLenAsFloat)]
|
||||||
|
|
||||||
t := table.NewWriter()
|
t := table.NewWriter()
|
||||||
t.SetOutputMirror(os.Stdout)
|
t.SetOutputMirror(os.Stdout)
|
||||||
t.SetStyle(table.StyleLight)
|
t.SetStyle(table.StyleLight)
|
||||||
t.SetColumnConfigs([]table.ColumnConfig{
|
t.SetColumnConfigs([]table.ColumnConfig{
|
||||||
{Number: 1, WidthMax: 80},
|
{Number: 1, WidthMax: 40},
|
||||||
})
|
})
|
||||||
|
|
||||||
t.AppendHeader(table.Row{
|
t.AppendHeader(table.Row{
|
||||||
"Response",
|
"Response",
|
||||||
"Count",
|
"Count",
|
||||||
"Min Time",
|
"Min",
|
||||||
"Max Time",
|
"Max",
|
||||||
"Average Time",
|
"Average",
|
||||||
|
"P90",
|
||||||
|
"P95",
|
||||||
|
"P99",
|
||||||
})
|
})
|
||||||
|
|
||||||
|
var roundPrecision int64 = 4
|
||||||
for key, durations := range mergedResponses {
|
for key, durations := range mergedResponses {
|
||||||
|
durations.Sort()
|
||||||
|
durationsLen := len(durations)
|
||||||
|
durationsLenAsFloat := float64(durationsLen - 1)
|
||||||
|
|
||||||
t.AppendRow(table.Row{
|
t.AppendRow(table.Row{
|
||||||
key,
|
key,
|
||||||
len(durations),
|
durationsLen,
|
||||||
utils.MinDuration(durations...),
|
utils.DurationRoundBy(*durations.First(), roundPrecision),
|
||||||
utils.MaxDuration(durations...),
|
utils.DurationRoundBy(*durations.Last(), roundPrecision),
|
||||||
utils.AvgDuration(durations...),
|
utils.DurationRoundBy(durations.Avg(), roundPrecision),
|
||||||
|
utils.DurationRoundBy(durations[int(0.90*durationsLenAsFloat)], roundPrecision),
|
||||||
|
utils.DurationRoundBy(durations[int(0.95*durationsLenAsFloat)], roundPrecision),
|
||||||
|
utils.DurationRoundBy(durations[int(0.99*durationsLenAsFloat)], roundPrecision),
|
||||||
})
|
})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(mergedResponses) > 1 {
|
||||||
t.AppendRow(table.Row{
|
t.AppendRow(table.Row{
|
||||||
"Total",
|
"Total",
|
||||||
totalCount,
|
total.Count,
|
||||||
totalMinDuration,
|
utils.DurationRoundBy(total.Min, roundPrecision),
|
||||||
totalMaxDuration,
|
utils.DurationRoundBy(total.Max, roundPrecision),
|
||||||
totalDuration / time.Duration(totalCount),
|
utils.DurationRoundBy(total.Sum/time.Duration(total.Count), roundPrecision), // Average
|
||||||
|
utils.DurationRoundBy(total.P90, roundPrecision),
|
||||||
|
utils.DurationRoundBy(total.P95, roundPrecision),
|
||||||
|
utils.DurationRoundBy(total.P99, roundPrecision),
|
||||||
})
|
})
|
||||||
|
}
|
||||||
t.Render()
|
t.Render()
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,7 @@ package requests
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@ -74,7 +75,7 @@ func releaseDodos(
|
|||||||
requestCountPerDodo uint
|
requestCountPerDodo uint
|
||||||
dodosCount uint = requestConfig.GetValidDodosCountForRequests()
|
dodosCount uint = requestConfig.GetValidDodosCountForRequests()
|
||||||
dodosCountInt int = int(dodosCount)
|
dodosCountInt int = int(dodosCount)
|
||||||
requestCount uint = uint(requestConfig.RequestCount)
|
requestCount uint = requestConfig.RequestCount
|
||||||
responses = make([][]*Response, dodosCount)
|
responses = make([][]*Response, dodosCount)
|
||||||
increase = make(chan int64, requestCount)
|
increase = make(chan int64, requestCount)
|
||||||
)
|
)
|
||||||
@ -142,8 +143,7 @@ func sendRequest(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
*responseData = append(*responseData, &Response{
|
*responseData = append(*responseData, &Response{
|
||||||
StatusCode: 0,
|
Response: err.Error(),
|
||||||
Error: err,
|
|
||||||
Time: completedTime,
|
Time: completedTime,
|
||||||
})
|
})
|
||||||
increase <- 1
|
increase <- 1
|
||||||
@ -151,8 +151,7 @@ func sendRequest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
*responseData = append(*responseData, &Response{
|
*responseData = append(*responseData, &Response{
|
||||||
StatusCode: response.StatusCode(),
|
Response: strconv.Itoa(response.StatusCode()),
|
||||||
Error: nil,
|
|
||||||
Time: completedTime,
|
Time: completedTime,
|
||||||
})
|
})
|
||||||
increase <- 1
|
increase <- 1
|
||||||
|
41
types/durations.go
Normal file
41
types/durations.go
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
package types
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Durations []time.Duration
|
||||||
|
|
||||||
|
func (d Durations) Sort(ascending ...bool) {
|
||||||
|
// If ascending is provided and is false, sort in descending order
|
||||||
|
if len(ascending) > 0 && ascending[0] == false {
|
||||||
|
sort.Slice(d, func(i, j int) bool {
|
||||||
|
return d[i] > d[j]
|
||||||
|
})
|
||||||
|
} else { // Otherwise, sort in ascending order
|
||||||
|
sort.Slice(d, func(i, j int) bool {
|
||||||
|
return d[i] < d[j]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d Durations) First() *time.Duration {
|
||||||
|
return &d[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d Durations) Last() *time.Duration {
|
||||||
|
return &d[len(d)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d Durations) Sum() time.Duration {
|
||||||
|
sum := time.Duration(0)
|
||||||
|
for _, duration := range d {
|
||||||
|
sum += duration
|
||||||
|
}
|
||||||
|
return sum
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d Durations) Avg() time.Duration {
|
||||||
|
return d.Sum() / time.Duration(len(d))
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package utils
|
package types
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
@ -14,6 +14,8 @@ type Option[T NonNilT] interface {
|
|||||||
ValueOrErr() (T, error)
|
ValueOrErr() (T, error)
|
||||||
ValueOr(def T) T
|
ValueOr(def T) T
|
||||||
ValueOrPanic() T
|
ValueOrPanic() T
|
||||||
|
SetValue(value T)
|
||||||
|
SetNone()
|
||||||
UnmarshalJSON(data []byte) error
|
UnmarshalJSON(data []byte) error
|
||||||
}
|
}
|
||||||
|
|
@ -6,49 +6,80 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
func MarshalJSON(v any, maxSliceSize uint) string {
|
type TruncatedMarshaller struct {
|
||||||
rv := reflect.ValueOf(v)
|
Value interface{}
|
||||||
if rv.Kind() == reflect.Slice && rv.Len() == 0 {
|
MaxItems int
|
||||||
return "[]"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
data, err := json.MarshalIndent(truncateLists(v, int(maxSliceSize)), "", " ")
|
func (t TruncatedMarshaller) MarshalJSON() ([]byte, error) {
|
||||||
if err != nil {
|
val := reflect.ValueOf(t.Value)
|
||||||
return "{}"
|
|
||||||
|
if val.Kind() != reflect.Slice && val.Kind() != reflect.Array {
|
||||||
|
return json.Marshal(t.Value)
|
||||||
|
}
|
||||||
|
if val.Len() == 0 {
|
||||||
|
return []byte("[]"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return string(data)
|
length := val.Len()
|
||||||
|
if length <= t.MaxItems {
|
||||||
|
return json.Marshal(t.Value)
|
||||||
}
|
}
|
||||||
|
|
||||||
func truncateLists(v interface{}, maxItems int) interface{} {
|
truncated := make([]interface{}, t.MaxItems+1)
|
||||||
rv := reflect.ValueOf(v)
|
|
||||||
|
|
||||||
switch rv.Kind() {
|
for i := 0; i < t.MaxItems; i++ {
|
||||||
case reflect.Slice, reflect.Array:
|
truncated[i] = val.Index(i).Interface()
|
||||||
if rv.Len() > maxItems {
|
|
||||||
newSlice := reflect.MakeSlice(rv.Type(), maxItems, maxItems)
|
|
||||||
reflect.Copy(newSlice, rv.Slice(0, maxItems))
|
|
||||||
newSlice = reflect.Append(newSlice, reflect.ValueOf(fmt.Sprintf("...(%d more)", rv.Len()-maxItems)))
|
|
||||||
return newSlice.Interface()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
remaining := length - t.MaxItems
|
||||||
|
truncated[t.MaxItems] = fmt.Sprintf("+%d", remaining)
|
||||||
|
|
||||||
|
return json.Marshal(truncated)
|
||||||
|
}
|
||||||
|
|
||||||
|
func PrettyJSONMarshal(v interface{}, maxItems int, prefix, indent string) []byte {
|
||||||
|
truncated := processValue(v, maxItems)
|
||||||
|
d, _ := json.MarshalIndent(truncated, prefix, indent)
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
func processValue(v interface{}, maxItems int) interface{} {
|
||||||
|
val := reflect.ValueOf(v)
|
||||||
|
|
||||||
|
switch val.Kind() {
|
||||||
case reflect.Map:
|
case reflect.Map:
|
||||||
newMap := reflect.MakeMap(rv.Type())
|
newMap := make(map[string]interface{})
|
||||||
for _, key := range rv.MapKeys() {
|
iter := val.MapRange()
|
||||||
newMap.SetMapIndex(key, reflect.ValueOf(truncateLists(rv.MapIndex(key).Interface(), maxItems)))
|
for iter.Next() {
|
||||||
}
|
k := iter.Key().String()
|
||||||
return newMap.Interface()
|
newMap[k] = processValue(iter.Value().Interface(), maxItems)
|
||||||
case reflect.Struct:
|
|
||||||
newStruct := reflect.New(rv.Type()).Elem()
|
|
||||||
for i := 0; i < rv.NumField(); i++ {
|
|
||||||
newStruct.Field(i).Set(reflect.ValueOf(truncateLists(rv.Field(i).Interface(), maxItems)))
|
|
||||||
}
|
|
||||||
return newStruct.Interface()
|
|
||||||
case reflect.Ptr:
|
|
||||||
if rv.IsNil() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return truncateLists(rv.Elem().Interface(), maxItems)
|
|
||||||
}
|
}
|
||||||
|
return newMap
|
||||||
|
|
||||||
|
case reflect.Slice, reflect.Array:
|
||||||
|
return TruncatedMarshaller{Value: v, MaxItems: maxItems}
|
||||||
|
|
||||||
|
case reflect.Struct:
|
||||||
|
newMap := make(map[string]interface{})
|
||||||
|
t := val.Type()
|
||||||
|
for i := 0; i < t.NumField(); i++ {
|
||||||
|
field := t.Field(i)
|
||||||
|
if field.IsExported() {
|
||||||
|
jsonTag := field.Tag.Get("json")
|
||||||
|
if jsonTag == "-" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fieldName := field.Name
|
||||||
|
if jsonTag != "" {
|
||||||
|
fieldName = jsonTag
|
||||||
|
}
|
||||||
|
newMap[fieldName] = processValue(val.Field(i).Interface(), maxItems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newMap
|
||||||
|
|
||||||
|
default:
|
||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
21
utils/int.go
Normal file
21
utils/int.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
type Number interface {
|
||||||
|
int | int8 | int16 | int32 | int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NumLen[T Number](n T) T {
|
||||||
|
if n < 0 {
|
||||||
|
n = -n
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
var count T = 0
|
||||||
|
for n > 0 {
|
||||||
|
n /= 10
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
@ -3,46 +3,12 @@ package utils
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
|
"github.com/fatih/color"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Colors = struct {
|
|
||||||
reset string
|
|
||||||
Red string
|
|
||||||
Green string
|
|
||||||
Yellow string
|
|
||||||
Orange string
|
|
||||||
Blue string
|
|
||||||
Magenta string
|
|
||||||
Cyan string
|
|
||||||
Gray string
|
|
||||||
White string
|
|
||||||
}{
|
|
||||||
reset: "\033[0m",
|
|
||||||
Red: "\033[31m",
|
|
||||||
Green: "\033[32m",
|
|
||||||
Yellow: "\033[33m",
|
|
||||||
Orange: "\033[38;5;208m",
|
|
||||||
Blue: "\033[34m",
|
|
||||||
Magenta: "\033[35m",
|
|
||||||
Cyan: "\033[36m",
|
|
||||||
Gray: "\033[37m",
|
|
||||||
White: "\033[97m",
|
|
||||||
}
|
|
||||||
|
|
||||||
func Colored(color string, a ...any) string {
|
|
||||||
return color + fmt.Sprint(a...) + Colors.reset
|
|
||||||
}
|
|
||||||
|
|
||||||
func PrintfC(color string, format string, a ...any) {
|
|
||||||
fmt.Printf(Colored(color, format), a...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func PrintlnC(color string, a ...any) {
|
|
||||||
fmt.Println(Colored(color, a...))
|
|
||||||
}
|
|
||||||
|
|
||||||
func PrintErr(err error) {
|
func PrintErr(err error) {
|
||||||
PrintlnC(Colors.Red, err.Error())
|
color.New(color.FgRed).Fprintln(os.Stderr, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
func PrintErrAndExit(err error) {
|
func PrintErrAndExit(err error) {
|
||||||
|
@ -2,30 +2,13 @@ package utils
|
|||||||
|
|
||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
func MinDuration(durations ...time.Duration) time.Duration {
|
func DurationRoundBy(duration time.Duration, n int64) time.Duration {
|
||||||
min := durations[0]
|
if durationLen := NumLen(duration.Nanoseconds()); durationLen > n {
|
||||||
for _, d := range durations {
|
roundNum := 1
|
||||||
if d < min {
|
for range durationLen - n {
|
||||||
min = d
|
roundNum *= 10
|
||||||
}
|
}
|
||||||
|
return duration.Round(time.Duration(roundNum))
|
||||||
}
|
}
|
||||||
return min
|
return duration
|
||||||
}
|
|
||||||
|
|
||||||
func MaxDuration(durations ...time.Duration) time.Duration {
|
|
||||||
max := durations[0]
|
|
||||||
for _, d := range durations {
|
|
||||||
if d > max {
|
|
||||||
max = d
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
|
|
||||||
func AvgDuration(durations ...time.Duration) time.Duration {
|
|
||||||
total := time.Duration(0)
|
|
||||||
for _, d := range durations {
|
|
||||||
total += d
|
|
||||||
}
|
|
||||||
return total / time.Duration(len(durations))
|
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user