mirror of
https://github.com/aykhans/dodo.git
synced 2025-09-05 10:43:37 +00:00
Compare commits
1 Commits
v0.5.6
...
f3fd8a4e7b
Author | SHA1 | Date | |
---|---|---|---|
![]() |
f3fd8a4e7b |
86
.github/workflows/publish-docker-image.yml
vendored
86
.github/workflows/publish-docker-image.yml
vendored
@@ -1,86 +0,0 @@
|
|||||||
name: publish-docker-image
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
# Match stable and pre versions, such as 'v1.0.0', 'v0.23.0-a', 'v0.23.0-a.2', 'v0.23.0-b', 'v0.23.0-b.3'
|
|
||||||
- "v*.*.*"
|
|
||||||
- "v*.*.*-a"
|
|
||||||
- "v*.*.*-a.*"
|
|
||||||
- "v*.*.*-b"
|
|
||||||
- "v*.*.*-b.*"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-and-push-stable-image:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: write
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v3
|
|
||||||
|
|
||||||
- name: Extract build args
|
|
||||||
# Extract version number and check if it's an pre version
|
|
||||||
run: |
|
|
||||||
if [[ "${GITHUB_REF_NAME}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
|
||||||
echo "PRE_RELEASE=false" >> $GITHUB_ENV
|
|
||||||
else
|
|
||||||
echo "PRE_RELEASE=true" >> $GITHUB_ENV
|
|
||||||
fi
|
|
||||||
echo "VERSION=${GITHUB_REF_NAME#v}" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Login to Docker Hub
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
username: aykhans
|
|
||||||
password: ${{ secrets.DOCKER_TOKEN }}
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
id: buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
with:
|
|
||||||
install: true
|
|
||||||
version: v0.9.1
|
|
||||||
|
|
||||||
# Metadata for stable versions
|
|
||||||
- name: Docker meta for stable
|
|
||||||
id: meta-stable
|
|
||||||
if: env.PRE_RELEASE == 'false'
|
|
||||||
uses: docker/metadata-action@v5
|
|
||||||
with:
|
|
||||||
images: |
|
|
||||||
aykhans/dodo
|
|
||||||
tags: |
|
|
||||||
type=semver,pattern={{version}},value=${{ env.VERSION }}
|
|
||||||
type=raw,value=stable
|
|
||||||
flavor: |
|
|
||||||
latest=true
|
|
||||||
labels: |
|
|
||||||
org.opencontainers.image.version=${{ env.VERSION }}
|
|
||||||
|
|
||||||
# Metadata for pre versions
|
|
||||||
- name: Docker meta for pre
|
|
||||||
id: meta-pre
|
|
||||||
if: env.PRE_RELEASE == 'true'
|
|
||||||
uses: docker/metadata-action@v5
|
|
||||||
with:
|
|
||||||
images: |
|
|
||||||
aykhans/dodo
|
|
||||||
tags: |
|
|
||||||
type=raw,value=${{ env.VERSION }}
|
|
||||||
labels: |
|
|
||||||
org.opencontainers.image.version=${{ env.VERSION }}
|
|
||||||
|
|
||||||
- name: Build and Push
|
|
||||||
id: docker_build
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: ./
|
|
||||||
file: ./Dockerfile
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
push: true
|
|
||||||
tags: ${{ steps.meta-stable.outputs.tags || steps.meta-pre.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta-stable.outputs.labels || steps.meta-pre.outputs.labels }}
|
|
@@ -1,4 +1,4 @@
|
|||||||
FROM golang:1.23.2-alpine AS builder
|
FROM golang:1.22.6-alpine AS builder
|
||||||
|
|
||||||
WORKDIR /dodo
|
WORKDIR /dodo
|
||||||
|
|
||||||
|
28
README.md
28
README.md
@@ -1,6 +1,6 @@
|
|||||||
<h1 align="center">Dodo is a simple and easy-to-use HTTP benchmarking tool.</h1>
|
<h1 align="center">Dodo is a simple and easy-to-use HTTP benchmarking tool.</h1>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img width="30%" height="30%" src="https://ftp.aykhans.me/web/client/pubshares/hB6VSdCnBCr8gFPeiMuCji/browse?path=%2Fdodo.png">
|
<img width="30%" height="30%" src="https://raw.githubusercontent.com/aykhans/dodo/main/assets/dodo.png">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
@@ -33,7 +33,7 @@ Follow the steps below to build dodo:
|
|||||||
3. **Build the project:**
|
3. **Build the project:**
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go build -ldflags "-s -w" -o dodo
|
go build -o dodo
|
||||||
```
|
```
|
||||||
|
|
||||||
This will generate an executable named `dodo` in the project directory.
|
This will generate an executable named `dodo` in the project directory.
|
||||||
@@ -49,7 +49,7 @@ dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
|||||||
```
|
```
|
||||||
With Docker:
|
With Docker:
|
||||||
```sh
|
```sh
|
||||||
docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
docker run --rm aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. JSON config file
|
### 2. JSON config file
|
||||||
@@ -58,14 +58,13 @@ You can find an example config structure in the [config.json](https://github.com
|
|||||||
{
|
{
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"url": "https://example.com",
|
"url": "https://example.com",
|
||||||
"no_proxy_check": false,
|
"timeout": 10000,
|
||||||
"timeout": 2000,
|
"dodos_count": 50,
|
||||||
"dodos": 10,
|
"request_count": 1000,
|
||||||
"requests": 1000,
|
|
||||||
"params": {},
|
"params": {},
|
||||||
"headers": {},
|
"headers": {},
|
||||||
"cookies": {},
|
"cookies": {},
|
||||||
"body": [],
|
"body": "",
|
||||||
"proxies": [
|
"proxies": [
|
||||||
{
|
{
|
||||||
"url": "http://example.com:8080",
|
"url": "http://example.com:8080",
|
||||||
@@ -78,14 +77,14 @@ You can find an example config structure in the [config.json](https://github.com
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 2000 milliseconds:
|
Send 1000 GET requests to https://example.com with 5 parallel dodos (threads) and a timeout of 10000 milliseconds:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dodo -c /path/config.json
|
dodo -c /path/config.json
|
||||||
```
|
```
|
||||||
With Docker:
|
With Docker:
|
||||||
```sh
|
```sh
|
||||||
docker run --rm -i -v ./path/config.json:/dodo/config.json aykhans/dodo
|
docker run --rm -v ./path/config.json:/dodo/config.json -i aykhans/dodo
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. Both (CLI & JSON)
|
### 3. Both (CLI & JSON)
|
||||||
@@ -96,22 +95,21 @@ 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 -i -v ./path/config.json:/dodo/config.json aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
|
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
|
||||||
```
|
```
|
||||||
|
|
||||||
## CLI and JSON Config Parameters
|
## CLI and JSON Config Parameters
|
||||||
If the Headers, Params, Cookies and Body fields have multiple values, each request will choose a random value from the list.
|
If the Headers, Params, Cookies and Body 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 | JSON config file | CLI Flag | CLI Short Flag | Type | Description | Default |
|
||||||
| --------------------- | ---------------- | --------------- | -------------- | -------------------------------- | ------------------------------------------------------------------- | ----------- |
|
| ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- |
|
||||||
| Config file | - | --config-file | -c | String | Path to the JSON config file | - |
|
| Config file | - | --config-file | -c | String | Path to the JSON config file | - |
|
||||||
| 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 |
|
||||||
| Requests | requests | --requests | -r | Integer | Total number of requests to send | 1000 |
|
| Request count | request_count | --request-count | -r | Integer | Total number of requests to send | 1000 |
|
||||||
| Dodos (Threads) | dodos | --dodos | -d | Integer | Number of dodos (threads) to send requests in parallel | 1 |
|
| Dodos count (Threads) | dodos_count | --dodos-count | -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 |
|
|
||||||
| Params | params | - | - | Key-Value {String: [String]} | Request parameters | - |
|
| Params | params | - | - | Key-Value {String: [String]} | Request parameters | - |
|
||||||
| Headers | headers | - | - | Key-Value {String: [String]} | Request headers | - |
|
| Headers | headers | - | - | Key-Value {String: [String]} | Request headers | - |
|
||||||
| Cookies | cookies | - | - | Key-Value {String: [String]} | Request cookies | - |
|
| Cookies | cookies | - | - | Key-Value {String: [String]} | Request cookies | - |
|
||||||
|
BIN
assets/dodo.png
Normal file
BIN
assets/dodo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 230 KiB |
@@ -1,14 +1,13 @@
|
|||||||
{
|
{
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"url": "https://example.com",
|
"url": "https://example.com",
|
||||||
"no_proxy_check": false,
|
|
||||||
"timeout": 10000,
|
"timeout": 10000,
|
||||||
"dodos": 1,
|
"dodos_count": 50,
|
||||||
"requests": 1,
|
"request_count": 1000,
|
||||||
"params": {},
|
"params": {},
|
||||||
"headers": {},
|
"headers": {},
|
||||||
"cookies": {},
|
"cookies": {},
|
||||||
"body": [],
|
"body": [""],
|
||||||
"proxies": [
|
"proxies": [
|
||||||
{
|
{
|
||||||
"url": "http://example.com:8080",
|
"url": "http://example.com:8080",
|
||||||
|
114
config/config.go
114
config/config.go
@@ -1,27 +1,30 @@
|
|||||||
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.6"
|
VERSION string = "0.5.1"
|
||||||
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 = 1
|
DefaultRequestCount uint = 1000
|
||||||
MaxDodosCountForProxies uint = 20 // Max dodos count for proxy check
|
MaxDodosCountForProxies uint = 20 // Max dodos count for proxy check
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type IConfig interface {
|
||||||
|
MergeConfigs(newConfig IConfig) IConfig
|
||||||
|
}
|
||||||
|
|
||||||
type RequestConfig struct {
|
type RequestConfig struct {
|
||||||
Method string
|
Method string
|
||||||
URL *url.URL
|
URL *url.URL
|
||||||
@@ -34,7 +37,6 @@ type RequestConfig struct {
|
|||||||
Proxies []Proxy
|
Proxies []Proxy
|
||||||
Body []string
|
Body []string
|
||||||
Yes bool
|
Yes bool
|
||||||
NoProxyCheck bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (config *RequestConfig) Print() {
|
func (config *RequestConfig) Print() {
|
||||||
@@ -42,48 +44,29 @@ 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["User-Agent"] = []string{DefaultUserAgent}
|
|
||||||
for k, v := range config.Headers {
|
|
||||||
newHeaders[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
t.AppendHeader(table.Row{"Request Configuration"})
|
t.AppendHeader(table.Row{"Request Configuration"})
|
||||||
t.AppendRow(table.Row{"Method", config.Method})
|
t.AppendRow(table.Row{"Method", config.Method})
|
||||||
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", config.Timeout})
|
t.AppendRow(table.Row{"Timeout", fmt.Sprintf("%dms", config.Timeout/time.Millisecond)})
|
||||||
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{"Request", config.RequestCount})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Params", string(utils.PrettyJSONMarshal(config.Params, 3, "", " "))})
|
t.AppendRow(table.Row{"Params", utils.MarshalJSON(config.Params, 3)})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Headers", string(utils.PrettyJSONMarshal(newHeaders, 3, "", " "))})
|
t.AppendRow(table.Row{"Headers", utils.MarshalJSON(config.Headers, 3)})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Cookies", string(utils.PrettyJSONMarshal(config.Cookies, 3, "", " "))})
|
t.AppendRow(table.Row{"Cookies", utils.MarshalJSON(config.Cookies, 3)})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Proxies", string(utils.PrettyJSONMarshal(config.Proxies, 3, "", " "))})
|
t.AppendRow(table.Row{"Proxies Count", len(config.Proxies)})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Proxy Check", !config.NoProxyCheck})
|
t.AppendRow(table.Row{"Body", utils.MarshalJSON(config.Body, 3)})
|
||||||
t.AppendSeparator()
|
|
||||||
t.AppendRow(table.Row{"Body", string(utils.PrettyJSONMarshal(config.Body, 3, "", " "))})
|
|
||||||
|
|
||||||
t.Render()
|
t.Render()
|
||||||
}
|
}
|
||||||
@@ -107,29 +90,8 @@ 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" validate:"gte=1"`
|
DodosCount uint `json:"dodos_count" validate:"gte=1"`
|
||||||
RequestCount uint `json:"requests" validation_name:"request-count" validate:"gte=1"`
|
RequestCount uint `json:"request_count" validation_name:"request-count" validate:"gte=1"`
|
||||||
NoProxyCheck Option[bool] `json:"no_proxy_check"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConfig(
|
|
||||||
method string,
|
|
||||||
timeout uint32,
|
|
||||||
dodosCount uint,
|
|
||||||
requestCount uint,
|
|
||||||
noProxyCheck Option[bool],
|
|
||||||
) *Config {
|
|
||||||
if noProxyCheck == nil {
|
|
||||||
noProxyCheck = NewNoneOption[bool]()
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Config{
|
|
||||||
Method: method,
|
|
||||||
Timeout: timeout,
|
|
||||||
DodosCount: dodosCount,
|
|
||||||
RequestCount: requestCount,
|
|
||||||
NoProxyCheck: noProxyCheck,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (config *Config) MergeConfigs(newConfig *Config) {
|
func (config *Config) MergeConfigs(newConfig *Config) {
|
||||||
@@ -148,9 +110,6 @@ func (config *Config) MergeConfigs(newConfig *Config) {
|
|||||||
if newConfig.RequestCount != 0 {
|
if newConfig.RequestCount != 0 {
|
||||||
config.RequestCount = newConfig.RequestCount
|
config.RequestCount = newConfig.RequestCount
|
||||||
}
|
}
|
||||||
if !newConfig.NoProxyCheck.IsNone() {
|
|
||||||
config.NoProxyCheck = newConfig.NoProxyCheck
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (config *Config) SetDefaults() {
|
func (config *Config) SetDefaults() {
|
||||||
@@ -166,9 +125,6 @@ func (config *Config) SetDefaults() {
|
|||||||
if config.RequestCount == 0 {
|
if config.RequestCount == 0 {
|
||||||
config.RequestCount = DefaultRequestCount
|
config.RequestCount = DefaultRequestCount
|
||||||
}
|
}
|
||||||
if config.NoProxyCheck.IsNone() {
|
|
||||||
config.NoProxyCheck = NewOption(false)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
@@ -178,7 +134,7 @@ type Proxy struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type JSONConfig struct {
|
type JSONConfig struct {
|
||||||
*Config
|
Config
|
||||||
Params map[string][]string `json:"params"`
|
Params map[string][]string `json:"params"`
|
||||||
Headers map[string][]string `json:"headers"`
|
Headers map[string][]string `json:"headers"`
|
||||||
Cookies map[string][]string `json:"cookies"`
|
Cookies map[string][]string `json:"cookies"`
|
||||||
@@ -186,21 +142,8 @@ type JSONConfig struct {
|
|||||||
Body []string `json:"body"`
|
Body []string `json:"body"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewJSONConfig(
|
|
||||||
config *Config,
|
|
||||||
params map[string][]string,
|
|
||||||
headers map[string][]string,
|
|
||||||
cookies map[string][]string,
|
|
||||||
proxies []Proxy,
|
|
||||||
body []string,
|
|
||||||
) *JSONConfig {
|
|
||||||
return &JSONConfig{
|
|
||||||
config, params, headers, cookies, proxies, body,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (config *JSONConfig) MergeConfigs(newConfig *JSONConfig) {
|
func (config *JSONConfig) MergeConfigs(newConfig *JSONConfig) {
|
||||||
config.Config.MergeConfigs(newConfig.Config)
|
config.Config.MergeConfigs(&newConfig.Config)
|
||||||
if len(newConfig.Params) != 0 {
|
if len(newConfig.Params) != 0 {
|
||||||
config.Params = newConfig.Params
|
config.Params = newConfig.Params
|
||||||
}
|
}
|
||||||
@@ -219,27 +162,14 @@ func (config *JSONConfig) MergeConfigs(newConfig *JSONConfig) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type CLIConfig struct {
|
type CLIConfig struct {
|
||||||
*Config
|
Config
|
||||||
Yes Option[bool] `json:"yes" validate:"omitempty"`
|
Yes 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(
|
|
||||||
config *Config,
|
|
||||||
yes Option[bool],
|
|
||||||
configFile string,
|
|
||||||
) *CLIConfig {
|
|
||||||
return &CLIConfig{
|
|
||||||
config, yes, configFile,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (config *CLIConfig) MergeConfigs(newConfig *CLIConfig) {
|
func (config *CLIConfig) MergeConfigs(newConfig *CLIConfig) {
|
||||||
config.Config.MergeConfigs(newConfig.Config)
|
config.Config.MergeConfigs(&newConfig.Config)
|
||||||
if newConfig.ConfigFile != "" {
|
if newConfig.ConfigFile != "" {
|
||||||
config.ConfigFile = newConfig.ConfigFile
|
config.ConfigFile = newConfig.ConfigFile
|
||||||
}
|
}
|
||||||
if !newConfig.Yes.IsNone() {
|
|
||||||
config.Yes = newConfig.Yes
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@@ -19,6 +19,10 @@ 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:]
|
||||||
}
|
}
|
||||||
|
23
go.mod
23
go.mod
@@ -1,26 +1,29 @@
|
|||||||
module github.com/aykhans/dodo
|
module github.com/aykhans/dodo
|
||||||
|
|
||||||
go 1.23.2
|
go 1.22.6
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/go-playground/validator/v10 v10.24.0
|
github.com/go-playground/validator/v10 v10.22.1
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.5
|
github.com/jedib0t/go-pretty/v6 v6.6.0
|
||||||
github.com/valyala/fasthttp v1.58.0
|
github.com/spf13/cobra v1.8.1
|
||||||
golang.org/x/net v0.34.0
|
github.com/spf13/pflag v1.0.5
|
||||||
|
github.com/valyala/fasthttp v1.57.0
|
||||||
|
golang.org/x/net v0.30.0
|
||||||
)
|
)
|
||||||
|
|
||||||
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.8 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.4 // 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.15 // 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.32.0 // indirect
|
golang.org/x/crypto v0.28.0 // indirect
|
||||||
golang.org/x/sys v0.29.0 // indirect
|
golang.org/x/sys v0.26.0 // indirect
|
||||||
golang.org/x/term v0.28.0 // indirect
|
golang.org/x/term v0.25.0 // indirect
|
||||||
golang.org/x/text v0.21.0 // indirect
|
golang.org/x/text v0.19.0 // indirect
|
||||||
)
|
)
|
||||||
|
45
go.sum
45
go.sum
@@ -1,19 +1,22 @@
|
|||||||
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.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s=
|
||||||
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.24.0 h1:KHQckvo8G6hlWnrPX4NJJ+aBfWNAE/HH+qdL2cBpCmg=
|
github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA=
|
||||||
github.com/go-playground/validator/v10 v10.24.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=
|
github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.5 h1:9PgMJOVBedpgYLI56jQRJYqngxYAAzfEUua+3NgSqAo=
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.5/go.mod h1:Uq/HrbhuFty5WSVNfjpQQe47x16RwVGXIveNGEyGtHs=
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/jedib0t/go-pretty/v6 v6.6.0 h1:wmZVuAcEkZRT+Aq1xXpE8IGat4vE5WXOMmBpbQqERXw=
|
||||||
|
github.com/jedib0t/go-pretty/v6 v6.6.0/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=
|
||||||
@@ -25,23 +28,29 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
|
|||||||
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/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
||||||
|
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 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
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.58.0 h1:GGB2dWxSbEprU9j0iMJHgdKYJVDyjrOwF9RE59PbRuE=
|
github.com/valyala/fasthttp v1.57.0 h1:Xw8SjWGEP/+wAAgyy5XTvgrWlOD1+TxbbvNADYCm1Tg=
|
||||||
github.com/valyala/fasthttp v1.58.0/go.mod h1:SYXvHHaFp7QZHGKSHmoMipInhrI5StHrhDTYVEjK/Kw=
|
github.com/valyala/fasthttp v1.57.0/go.mod h1:h6ZBaPRlzpZ6O3H5t2gEk1Qi33+TmLvfwgLLp0t9CpE=
|
||||||
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.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
|
golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw=
|
||||||
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
|
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
|
||||||
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
|
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
|
||||||
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
|
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
||||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
|
||||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/term v0.28.0 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
|
golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24=
|
||||||
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
|
golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M=
|
||||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
|
||||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||||
|
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=
|
||||||
|
23
main.go
23
main.go
@@ -21,19 +21,13 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
validator := validation.NewValidator()
|
validator := validation.NewValidator()
|
||||||
conf := config.NewConfig("", 0, 0, 0, nil)
|
conf := config.Config{}
|
||||||
jsonConf := config.NewJSONConfig(
|
jsonConf := config.JSONConfig{}
|
||||||
config.NewConfig("", 0, 0, 0, nil), nil, nil, nil, nil, nil,
|
|
||||||
)
|
|
||||||
|
|
||||||
cliConf, err := readers.CLIConfigReader()
|
cliConf, err := readers.CLIConfigReader()
|
||||||
if err != nil {
|
if err != nil || cliConf == 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(
|
||||||
@@ -57,11 +51,11 @@ func main() {
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
jsonConf = jsonConfNew
|
jsonConf = *jsonConfNew
|
||||||
conf.MergeConfigs(jsonConf.Config)
|
conf.MergeConfigs(&jsonConf.Config)
|
||||||
}
|
}
|
||||||
|
|
||||||
conf.MergeConfigs(cliConf.Config)
|
conf.MergeConfigs(&cliConf.Config)
|
||||||
conf.SetDefaults()
|
conf.SetDefaults()
|
||||||
if err := validator.Struct(conf); err != nil {
|
if err := validator.Struct(conf); err != nil {
|
||||||
utils.PrintErrAndExit(
|
utils.PrintErrAndExit(
|
||||||
@@ -86,11 +80,10 @@ func main() {
|
|||||||
Cookies: jsonConf.Cookies,
|
Cookies: jsonConf.Cookies,
|
||||||
Proxies: jsonConf.Proxies,
|
Proxies: jsonConf.Proxies,
|
||||||
Body: jsonConf.Body,
|
Body: jsonConf.Body,
|
||||||
Yes: cliConf.Yes.ValueOr(false),
|
Yes: cliConf.Yes,
|
||||||
NoProxyCheck: conf.NoProxyCheck.ValueOr(false),
|
|
||||||
}
|
}
|
||||||
requestConf.Print()
|
requestConf.Print()
|
||||||
if !cliConf.Yes.ValueOr(false) {
|
if !cliConf.Yes {
|
||||||
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...")
|
||||||
|
153
readers/cli.go
153
readers/cli.go
@@ -1,128 +1,75 @@
|
|||||||
package readers
|
package readers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"flag"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/aykhans/dodo/config"
|
"github.com/aykhans/dodo/config"
|
||||||
. "github.com/aykhans/dodo/types"
|
"github.com/aykhans/dodo/custom_errors"
|
||||||
"github.com/aykhans/dodo/utils"
|
"github.com/aykhans/dodo/utils"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
"github.com/spf13/pflag"
|
||||||
)
|
)
|
||||||
|
|
||||||
const usageText = `Usage:
|
func CLIConfigReader() (*config.CLIConfig, error) {
|
||||||
dodo [flags]
|
var (
|
||||||
|
returnNil = false
|
||||||
Examples:
|
cliConfig = &config.CLIConfig{}
|
||||||
|
dodosCount uint
|
||||||
Simple usage only with URL:
|
requestCount uint
|
||||||
|
timeout uint32
|
||||||
|
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`,
|
||||||
|
Short: `
|
||||||
Flags:
|
██████████ ███████ ██████████ ███████
|
||||||
-h, --help help for dodo
|
░░███░░░░███ ███░░░░░███ ░░███░░░░███ ███░░░░░███
|
||||||
-v, --version version for dodo
|
░███ ░░███ ███ ░░███ ░███ ░░███ ███ ░░███
|
||||||
-c, --config-file string Path to the config file
|
░███ ░███░███ ░███ ░███ ░███░███ ░███
|
||||||
-d, --dodos uint Number of dodos(threads) (default %d)
|
░███ ░███░███ ░███ ░███ ░███░███ ░███
|
||||||
-m, --method string HTTP Method (default %s)
|
░███ ███ ░░███ ███ ░███ ███ ░░███ ███
|
||||||
-r, --request uint Number of total requests (default %d)
|
██████████ ░░░███████░ ██████████ ░░░███████░
|
||||||
-t, --timeout uint32 Timeout for each request in milliseconds (default %d)
|
░░░░░░░░░░ ░░░░░░░ ░░░░░░░░░░ ░░░░░░░
|
||||||
-u, --url string URL for stress testing
|
`,
|
||||||
--no-proxy-check bool Do not check for proxies (default false)
|
Run: func(cmd *cobra.Command, args []string) {},
|
||||||
-y, --yes bool Answer yes to all questions (default false)`
|
SilenceErrors: true,
|
||||||
|
SilenceUsage: true,
|
||||||
func CLIConfigReader() (*config.CLIConfig, error) {
|
Version: config.VERSION,
|
||||||
flag.Usage = func() {
|
}
|
||||||
fmt.Printf(
|
|
||||||
usageText+"\n",
|
|
||||||
config.DefaultDodosCount,
|
|
||||||
config.DefaultMethod,
|
|
||||||
config.DefaultRequestCount,
|
|
||||||
config.DefaultTimeout,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
rootCmd.Flags().StringVarP(&cliConfig.ConfigFile, "config-file", "c", "", "Path to the config file")
|
||||||
|
rootCmd.Flags().BoolVarP(&cliConfig.Yes, "yes", "y", false, "Answer yes to all questions")
|
||||||
|
rootCmd.Flags().StringVarP(&cliConfig.Method, "method", "m", "", fmt.Sprintf("HTTP Method (default %s)", config.DefaultMethod))
|
||||||
|
rootCmd.Flags().StringVarP(&cliConfig.URL, "url", "u", "", "URL for stress testing")
|
||||||
|
rootCmd.Flags().UintVarP(&dodosCount, "dodos-count", "d", config.DefaultDodosCount, "Number of dodos(threads)")
|
||||||
|
rootCmd.Flags().UintVarP(&requestCount, "request-count", "r", config.DefaultRequestCount, "Number of total requests")
|
||||||
|
rootCmd.Flags().Uint32VarP(&timeout, "timeout", "t", config.DefaultTimeout, "Timeout for each request in milliseconds")
|
||||||
|
if err := rootCmd.Execute(); err != nil {
|
||||||
|
utils.PrintErr(err)
|
||||||
|
rootCmd.Println(rootCmd.UsageString())
|
||||||
|
return nil, customerrors.CobraErrorFormater(err)
|
||||||
}
|
}
|
||||||
|
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 "version", "v":
|
case "help":
|
||||||
fmt.Printf("dodo version %s\n", config.VERSION)
|
|
||||||
returnNil = true
|
returnNil = true
|
||||||
case "config-file", "c":
|
case "version":
|
||||||
cliConfig.ConfigFile = configFile
|
returnNil = true
|
||||||
case "yes", "y":
|
case "dodos-count":
|
||||||
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 "requests", "r":
|
case "request-count":
|
||||||
cliConfig.RequestCount = requestsCount
|
cliConfig.RequestCount = requestCount
|
||||||
case "timeout", "t":
|
case "timeout":
|
||||||
var maxUint32 uint = 4294967295
|
cliConfig.Timeout = timeout
|
||||||
if timeout > maxUint32 {
|
|
||||||
utils.PrintfC(utils.Colors.Yellow, "timeout value is too large, setting to %d\n", maxUint32)
|
|
||||||
timeout = maxUint32
|
|
||||||
}
|
|
||||||
cliConfig.Timeout = uint32(timeout)
|
|
||||||
case "no-proxy-check":
|
|
||||||
cliConfig.NoProxyCheck.SetValue(noProxyCheck)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if returnNil {
|
if returnNil {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
@@ -5,7 +5,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/aykhans/dodo/config"
|
"github.com/aykhans/dodo/config"
|
||||||
customerrors "github.com/aykhans/dodo/custom_errors"
|
"github.com/aykhans/dodo/custom_errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
func JSONConfigReader(filePath string) (*config.JSONConfig, error) {
|
func JSONConfigReader(filePath string) (*config.JSONConfig, error) {
|
||||||
@@ -13,10 +13,7 @@ func JSONConfigReader(filePath string) (*config.JSONConfig, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, customerrors.OSErrorFormater(err)
|
return nil, customerrors.OSErrorFormater(err)
|
||||||
}
|
}
|
||||||
jsonConf := config.NewJSONConfig(
|
jsonConf := &config.JSONConfig{}
|
||||||
config.NewConfig("", 0, 0, 0, nil),
|
|
||||||
nil, nil, nil, nil, nil,
|
|
||||||
)
|
|
||||||
err = json.Unmarshal(data, &jsonConf)
|
err = json.Unmarshal(data, &jsonConf)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@@ -26,42 +26,11 @@ func getClients(
|
|||||||
dodosCount uint,
|
dodosCount uint,
|
||||||
maxConns uint,
|
maxConns uint,
|
||||||
yes bool,
|
yes bool,
|
||||||
noProxyCheck bool,
|
|
||||||
URL *url.URL,
|
URL *url.URL,
|
||||||
) []*fasthttp.HostClient {
|
) []*fasthttp.HostClient {
|
||||||
isTLS := URL.Scheme == "https"
|
isTLS := URL.Scheme == "https"
|
||||||
|
|
||||||
if proxiesLen := len(proxies); proxiesLen > 0 {
|
if len(proxies) > 0 {
|
||||||
// If noProxyCheck is true, we will return the clients without checking the proxies.
|
|
||||||
if noProxyCheck {
|
|
||||||
clients := make([]*fasthttp.HostClient, 0, proxiesLen)
|
|
||||||
addr := URL.Host
|
|
||||||
if isTLS && URL.Port() == "" {
|
|
||||||
addr += ":443"
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
dialFunc, err := getDialFunc(&proxy, timeout)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
clients = append(clients, &fasthttp.HostClient{
|
|
||||||
MaxConns: int(maxConns),
|
|
||||||
IsTLS: isTLS,
|
|
||||||
Addr: addr,
|
|
||||||
Dial: dialFunc,
|
|
||||||
MaxIdleConnDuration: timeout,
|
|
||||||
MaxConnDuration: timeout,
|
|
||||||
WriteTimeout: timeout,
|
|
||||||
ReadTimeout: timeout,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return clients
|
|
||||||
}
|
|
||||||
|
|
||||||
// Else, we will check the proxies and return the active ones.
|
|
||||||
activeProxyClients := getActiveProxyClients(
|
activeProxyClients := getActiveProxyClients(
|
||||||
ctx, proxies, timeout, dodosCount, maxConns, URL,
|
ctx, proxies, timeout, dodosCount, maxConns, URL,
|
||||||
)
|
)
|
||||||
|
@@ -26,6 +26,7 @@ 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,108 +1,85 @@
|
|||||||
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 {
|
||||||
Response string
|
StatusCode int
|
||||||
|
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, average time, and latency percentiles.
|
// response count, minimum time, maximum time, and average time.
|
||||||
func (responses Responses) Print() {
|
func (respones Responses) Print() {
|
||||||
total := struct {
|
var (
|
||||||
Count int
|
totalMinDuration time.Duration = respones[0].Time
|
||||||
Min time.Duration
|
totalMaxDuration time.Duration = respones[0].Time
|
||||||
Max time.Duration
|
totalDuration time.Duration
|
||||||
Sum time.Duration
|
totalCount int = len(respones)
|
||||||
P90 time.Duration
|
)
|
||||||
P95 time.Duration
|
mergedResponses := make(map[string][]time.Duration)
|
||||||
P99 time.Duration
|
|
||||||
}{
|
|
||||||
Count: len(responses),
|
|
||||||
Min: responses[0].Time,
|
|
||||||
Max: responses[0].Time,
|
|
||||||
}
|
|
||||||
mergedResponses := make(map[string]Durations)
|
|
||||||
var allDurations Durations
|
|
||||||
|
|
||||||
for _, response := range responses {
|
for _, response := range respones {
|
||||||
if response.Time < total.Min {
|
if response.Time < totalMinDuration {
|
||||||
total.Min = response.Time
|
totalMinDuration = response.Time
|
||||||
}
|
}
|
||||||
if response.Time > total.Max {
|
if response.Time > totalMaxDuration {
|
||||||
total.Max = response.Time
|
totalMaxDuration = response.Time
|
||||||
}
|
}
|
||||||
total.Sum += response.Time
|
totalDuration += response.Time
|
||||||
|
|
||||||
mergedResponses[response.Response] = append(
|
if response.Error != nil {
|
||||||
mergedResponses[response.Response],
|
mergedResponses[response.Error.Error()] = append(
|
||||||
|
mergedResponses[response.Error.Error()],
|
||||||
|
response.Time,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
mergedResponses[fmt.Sprintf("%d", response.StatusCode)] = append(
|
||||||
|
mergedResponses[fmt.Sprintf("%d", response.StatusCode)],
|
||||||
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: 40},
|
{Number: 1, WidthMax: 80},
|
||||||
})
|
})
|
||||||
|
|
||||||
t.AppendHeader(table.Row{
|
t.AppendHeader(table.Row{
|
||||||
"Response",
|
"Response",
|
||||||
"Count",
|
"Count",
|
||||||
"Min",
|
"Min Time",
|
||||||
"Max",
|
"Max Time",
|
||||||
"Average",
|
"Average Time",
|
||||||
"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,
|
||||||
durationsLen,
|
len(durations),
|
||||||
utils.DurationRoundBy(*durations.First(), roundPrecision),
|
utils.MinDuration(durations...),
|
||||||
utils.DurationRoundBy(*durations.Last(), roundPrecision),
|
utils.MaxDuration(durations...),
|
||||||
utils.DurationRoundBy(durations.Avg(), roundPrecision),
|
utils.AvgDuration(durations...),
|
||||||
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",
|
||||||
total.Count,
|
totalCount,
|
||||||
utils.DurationRoundBy(total.Min, roundPrecision),
|
totalMinDuration,
|
||||||
utils.DurationRoundBy(total.Max, roundPrecision),
|
totalMaxDuration,
|
||||||
utils.DurationRoundBy(total.Sum/time.Duration(total.Count), roundPrecision), // Average
|
totalDuration / time.Duration(totalCount),
|
||||||
utils.DurationRoundBy(total.P90, roundPrecision),
|
|
||||||
utils.DurationRoundBy(total.P95, roundPrecision),
|
|
||||||
utils.DurationRoundBy(total.P99, roundPrecision),
|
|
||||||
})
|
})
|
||||||
}
|
|
||||||
t.Render()
|
t.Render()
|
||||||
}
|
}
|
||||||
|
@@ -2,7 +2,6 @@ package requests
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"strconv"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -39,7 +38,6 @@ func Run(ctx context.Context, requestConfig *config.RequestConfig) (Responses, e
|
|||||||
requestConfig.GetValidDodosCountForProxies(),
|
requestConfig.GetValidDodosCountForProxies(),
|
||||||
requestConfig.GetMaxConns(fasthttp.DefaultMaxConnsPerHost),
|
requestConfig.GetMaxConns(fasthttp.DefaultMaxConnsPerHost),
|
||||||
requestConfig.Yes,
|
requestConfig.Yes,
|
||||||
requestConfig.NoProxyCheck,
|
|
||||||
requestConfig.URL,
|
requestConfig.URL,
|
||||||
)
|
)
|
||||||
if clients == nil {
|
if clients == nil {
|
||||||
@@ -143,7 +141,8 @@ func sendRequest(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
*responseData = append(*responseData, &Response{
|
*responseData = append(*responseData, &Response{
|
||||||
Response: err.Error(),
|
StatusCode: 0,
|
||||||
|
Error: err,
|
||||||
Time: completedTime,
|
Time: completedTime,
|
||||||
})
|
})
|
||||||
increase <- 1
|
increase <- 1
|
||||||
@@ -151,7 +150,8 @@ func sendRequest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
*responseData = append(*responseData, &Response{
|
*responseData = append(*responseData, &Response{
|
||||||
Response: strconv.Itoa(response.StatusCode()),
|
StatusCode: response.StatusCode(),
|
||||||
|
Error: nil,
|
||||||
Time: completedTime,
|
Time: completedTime,
|
||||||
})
|
})
|
||||||
increase <- 1
|
increase <- 1
|
||||||
|
@@ -1,41 +0,0 @@
|
|||||||
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,89 +0,0 @@
|
|||||||
package types
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type NonNilT interface {
|
|
||||||
~int | ~float64 | ~string | ~bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type Option[T NonNilT] interface {
|
|
||||||
IsNone() bool
|
|
||||||
ValueOrErr() (T, error)
|
|
||||||
ValueOr(def T) T
|
|
||||||
ValueOrPanic() T
|
|
||||||
SetValue(value T)
|
|
||||||
SetNone()
|
|
||||||
UnmarshalJSON(data []byte) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't call this struct directly, use NewOption[T] or NewNoneOption[T] instead.
|
|
||||||
type option[T NonNilT] struct {
|
|
||||||
// value holds the actual value of the Option if it is not None.
|
|
||||||
value T
|
|
||||||
// none indicates whether the Option is None (i.e., has no value).
|
|
||||||
none bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *option[T]) IsNone() bool {
|
|
||||||
return o.none
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the Option is None, it will return zero value of the type and an error.
|
|
||||||
func (o *option[T]) ValueOrErr() (T, error) {
|
|
||||||
if o.IsNone() {
|
|
||||||
return o.value, errors.New("Option is None")
|
|
||||||
}
|
|
||||||
return o.value, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the Option is None, it will return the default value.
|
|
||||||
func (o *option[T]) ValueOr(def T) T {
|
|
||||||
if o.IsNone() {
|
|
||||||
return def
|
|
||||||
}
|
|
||||||
return o.value
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the Option is None, it will panic.
|
|
||||||
func (o *option[T]) ValueOrPanic() T {
|
|
||||||
if o.IsNone() {
|
|
||||||
panic("Option is None")
|
|
||||||
}
|
|
||||||
return o.value
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *option[T]) SetValue(value T) {
|
|
||||||
o.value = value
|
|
||||||
o.none = false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *option[T]) SetNone() {
|
|
||||||
var zeroValue T
|
|
||||||
o.value = zeroValue
|
|
||||||
o.none = true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o *option[T]) UnmarshalJSON(data []byte) error {
|
|
||||||
if string(data) == "null" || len(data) == 0 {
|
|
||||||
o.SetNone()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := json.Unmarshal(data, &o.value); err != nil {
|
|
||||||
o.SetNone()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
o.none = false
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewOption[T NonNilT](value T) *option[T] {
|
|
||||||
return &option[T]{value: value}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewNoneOption[T NonNilT]() *option[T] {
|
|
||||||
return &option[T]{none: true}
|
|
||||||
}
|
|
@@ -6,80 +6,49 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
type TruncatedMarshaller struct {
|
func MarshalJSON(v any, maxSliceSize uint) string {
|
||||||
Value interface{}
|
rv := reflect.ValueOf(v)
|
||||||
MaxItems int
|
if rv.Kind() == reflect.Slice && rv.Len() == 0 {
|
||||||
|
return "[]"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t TruncatedMarshaller) MarshalJSON() ([]byte, error) {
|
data, err := json.MarshalIndent(truncateLists(v, int(maxSliceSize)), "", " ")
|
||||||
val := reflect.ValueOf(t.Value)
|
if err != nil {
|
||||||
|
return "{}"
|
||||||
if val.Kind() != reflect.Slice && val.Kind() != reflect.Array {
|
|
||||||
return json.Marshal(t.Value)
|
|
||||||
}
|
|
||||||
if val.Len() == 0 {
|
|
||||||
return []byte("[]"), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
length := val.Len()
|
return string(data)
|
||||||
if length <= t.MaxItems {
|
|
||||||
return json.Marshal(t.Value)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
truncated := make([]interface{}, t.MaxItems+1)
|
func truncateLists(v interface{}, maxItems int) interface{} {
|
||||||
|
rv := reflect.ValueOf(v)
|
||||||
for i := 0; i < t.MaxItems; i++ {
|
|
||||||
truncated[i] = val.Index(i).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:
|
|
||||||
newMap := make(map[string]interface{})
|
|
||||||
iter := val.MapRange()
|
|
||||||
for iter.Next() {
|
|
||||||
k := iter.Key().String()
|
|
||||||
newMap[k] = processValue(iter.Value().Interface(), maxItems)
|
|
||||||
}
|
|
||||||
return newMap
|
|
||||||
|
|
||||||
|
switch rv.Kind() {
|
||||||
case reflect.Slice, reflect.Array:
|
case reflect.Slice, reflect.Array:
|
||||||
return TruncatedMarshaller{Value: v, MaxItems: maxItems}
|
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()
|
||||||
|
}
|
||||||
|
case reflect.Map:
|
||||||
|
newMap := reflect.MakeMap(rv.Type())
|
||||||
|
for _, key := range rv.MapKeys() {
|
||||||
|
newMap.SetMapIndex(key, reflect.ValueOf(truncateLists(rv.MapIndex(key).Interface(), maxItems)))
|
||||||
|
}
|
||||||
|
return newMap.Interface()
|
||||||
case reflect.Struct:
|
case reflect.Struct:
|
||||||
newMap := make(map[string]interface{})
|
newStruct := reflect.New(rv.Type()).Elem()
|
||||||
t := val.Type()
|
for i := 0; i < rv.NumField(); i++ {
|
||||||
for i := 0; i < t.NumField(); i++ {
|
newStruct.Field(i).Set(reflect.ValueOf(truncateLists(rv.Field(i).Interface(), maxItems)))
|
||||||
field := t.Field(i)
|
|
||||||
if field.IsExported() {
|
|
||||||
jsonTag := field.Tag.Get("json")
|
|
||||||
if jsonTag == "-" {
|
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
fieldName := field.Name
|
return newStruct.Interface()
|
||||||
if jsonTag != "" {
|
case reflect.Ptr:
|
||||||
fieldName = jsonTag
|
if rv.IsNil() {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
newMap[fieldName] = processValue(val.Field(i).Interface(), maxItems)
|
return truncateLists(rv.Elem().Interface(), maxItems)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return newMap
|
|
||||||
|
|
||||||
default:
|
|
||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
21
utils/int.go
21
utils/int.go
@@ -1,21 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
@@ -2,13 +2,30 @@ package utils
|
|||||||
|
|
||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
func DurationRoundBy(duration time.Duration, n int64) time.Duration {
|
func MinDuration(durations ...time.Duration) time.Duration {
|
||||||
if durationLen := NumLen(duration.Nanoseconds()); durationLen > n {
|
min := durations[0]
|
||||||
roundNum := 1
|
for _, d := range durations {
|
||||||
for range durationLen - n {
|
if d < min {
|
||||||
roundNum *= 10
|
min = d
|
||||||
}
|
}
|
||||||
return duration.Round(time.Duration(roundNum))
|
|
||||||
}
|
}
|
||||||
return duration
|
return min
|
||||||
|
}
|
||||||
|
|
||||||
|
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