59 Commits

Author SHA1 Message Date
779d5e9b18 Merge pull request #65 from aykhans/refactor/rename-cli-flags
🔨 Rename CLI flags
2025-01-03 13:27:24 +04:00
6a79d0b1d7 🔖 bump version to 0.5.502 2025-01-03 13:26:34 +04:00
1e53b8a7fb 📚 Update docs 2025-01-03 13:26:00 +04:00
0a8dbec739 🔨 Renama JSON parameters 2025-01-03 13:17:20 +04:00
3762890914 🔨 Rename CLI flags 2025-01-03 13:14:25 +04:00
ca6b3d4eb2 Merge pull request #64 from aykhans/bump/version
🔖 Bump version to 0.5.501
2024-12-25 02:08:59 +04:00
1ee06aacc3 🔖 Bump version to 0.5.501 2024-12-25 02:08:47 +04:00
3d5834a6a6 Merge pull request #63 from aykhans/fix/empty-slice
🐛 Return empty brackets instead of null when slice length is 0
2024-12-25 01:24:28 +04:00
f1521cbb74 💄 Update config table 2024-12-23 18:58:22 +04:00
40f8a1cc37 🐛 Return empty brackets instead of null when slice length is 0 2024-12-22 23:15:10 +04:00
8a3574cd48 Merge pull request #62 from aykhans/bumg/version
🔖 Bump version to v0.5.5
2024-12-22 22:03:09 +04:00
5a2a4c47b2 🔖 Bump version to v0.5.5 2024-12-22 22:02:57 +04:00
ff09a3365e Merge pull request #61 from aykhans/dependabot/go_modules/golang.org/x/net-0.33.0
Bump golang.org/x/net from 0.32.0 to 0.33.0
2024-12-20 18:17:30 +04:00
c83246abe4 Merge pull request #60 from aykhans/refactor/json-marshal
Refactor json marshal
2024-12-20 18:17:11 +04:00
efc4c62001 📚 Update docs 2024-12-20 18:16:25 +04:00
f567774e3a Bump golang.org/x/net from 0.32.0 to 0.33.0
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.32.0 to 0.33.0.
- [Commits](https://github.com/golang/net/compare/v0.32.0...v0.33.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-20 01:01:35 +00:00
d2bd60e3ff 🔨 Add custom 'WidthMaxEnforcer' to the table config 2024-12-20 01:21:26 +04:00
0fe782c768 🔨 Add 'PrettyJSONMarshal' function 2024-12-20 01:20:45 +04:00
b9dd14a588 Merge pull request #59 from aykhans/refactor/response-print
🔨 Round off durations before printing
2024-12-19 23:22:06 +04:00
18b1c7dae3 🔨 Round off durations before printing 2024-12-19 21:40:53 +04:00
77ddcf722a Merge pull request #58 from aykhans/hotfix/maxuint
🚑 Replace 'math.MaxUint32' with static variable
2024-12-18 23:47:53 +04:00
048cb68898 🚑 Replace 'math.MaxUint32' with static variable 2024-12-18 23:47:24 +04:00
fd5e87ee68 Merge pull request #57 from aykhans/refactor/cli-readers
🔨 Cobra package replaced with standard flag package
2024-12-18 23:40:03 +04:00
61b9ce943b 📚 Update docs 2024-12-18 23:38:52 +04:00
6fceb0094b 🔖 Bump version to 0.5.4 2024-12-18 23:31:13 +04:00
186683fce5 🔨Cobra package replaced with standard flag package 2024-12-18 20:58:14 +04:00
04e5b5f3eb Merge pull request #56 from aykhans/bump/version
Bump version to 0.5.3
2024-12-18 00:15:42 +04:00
2bebf09adb Bump version to 0.5.3 2024-12-18 00:15:31 +04:00
ebacebff16 Merge pull request #55 from aykhans/refactor/response-struct
🔨 Reduce memory usage of the 'Response' struct
2024-12-17 23:22:30 +04:00
575ca2913a 🔨 Reduce memory usage of the 'Response' struct 2024-12-17 23:07:25 +04:00
4686e26ede Merge pull request #53 from aykhans/feat/add-metrics
Add latency percentiles to the results table
2024-12-17 17:51:29 +04:00
bd33b2c6a2 Add latency percentiles to the results table 2024-12-17 03:42:52 +04:00
3068e0acae 🔨 Add 'types' package 2024-12-17 02:46:55 +04:00
7a40bbbd3c Merge pull request #51 from aykhans/dependabot/go_modules/go_modules-5a9c29dde4
Bump golang.org/x/crypto from 0.30.0 to 0.31.0 in the go_modules group
2024-12-16 22:59:56 +04:00
43c0bd2138 Bump golang.org/x/crypto from 0.30.0 to 0.31.0 in the go_modules group
Bumps the go_modules group with 1 update: [golang.org/x/crypto](https://github.com/golang/crypto).


Updates `golang.org/x/crypto` from 0.30.0 to 0.31.0
- [Commits](https://github.com/golang/crypto/compare/v0.30.0...v0.31.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: indirect
  dependency-group: go_modules
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-16 18:57:55 +00:00
fddeec1791 Merge pull request #50 from aykhans/dependabot/go_modules/github.com/jedib0t/go-pretty/v6-6.6.5
Bump github.com/jedib0t/go-pretty/v6 from 6.6.4 to 6.6.5
2024-12-16 22:56:58 +04:00
6f5fa1860c Bump github.com/jedib0t/go-pretty/v6 from 6.6.4 to 6.6.5
Bumps [github.com/jedib0t/go-pretty/v6](https://github.com/jedib0t/go-pretty) from 6.6.4 to 6.6.5.
- [Release notes](https://github.com/jedib0t/go-pretty/releases)
- [Commits](https://github.com/jedib0t/go-pretty/compare/v6.6.4...v6.6.5)

---
updated-dependencies:
- dependency-name: github.com/jedib0t/go-pretty/v6
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-16 00:53:59 +00:00
4480aed0f0 Merge pull request #48 from aykhans/dependabot/go_modules/github.com/valyala/fasthttp-1.58.0
Bump github.com/valyala/fasthttp from 1.57.0 to 1.58.0
2024-12-10 15:18:36 +04:00
f5144ac4be Bump github.com/valyala/fasthttp from 1.57.0 to 1.58.0
Bumps [github.com/valyala/fasthttp](https://github.com/valyala/fasthttp) from 1.57.0 to 1.58.0.
- [Release notes](https://github.com/valyala/fasthttp/releases)
- [Commits](https://github.com/valyala/fasthttp/compare/v1.57.0...v1.58.0)

---
updated-dependencies:
- dependency-name: github.com/valyala/fasthttp
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-10 10:53:23 +00:00
4a1051e08c Merge pull request #47 from aykhans/dependabot/go_modules/github.com/jedib0t/go-pretty/v6-6.6.4
Bump github.com/jedib0t/go-pretty/v6 from 6.6.3 to 6.6.4
2024-12-10 14:52:10 +04:00
2371986909 Bump github.com/jedib0t/go-pretty/v6 from 6.6.3 to 6.6.4
Bumps [github.com/jedib0t/go-pretty/v6](https://github.com/jedib0t/go-pretty) from 6.6.3 to 6.6.4.
- [Release notes](https://github.com/jedib0t/go-pretty/releases)
- [Commits](https://github.com/jedib0t/go-pretty/compare/v6.6.3...v6.6.4)

---
updated-dependencies:
- dependency-name: github.com/jedib0t/go-pretty/v6
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-10 00:26:21 +00:00
e9af46084d Merge pull request #45 from aykhans/docs/refactor
📚 Update README.md
2024-12-09 02:15:53 +04:00
cdaa63152f 📚 Update docs 2024-12-09 02:14:08 +04:00
16791421c7 📚 Update README.md 2024-12-09 02:11:52 +04:00
c90cfd8090 Merge pull request #44 from aykhans/dependabot/go_modules/golang.org/x/net-0.32.0
Bump golang.org/x/net from 0.31.0 to 0.32.0
2024-12-06 23:33:40 +04:00
1aaea8e437 Bump golang.org/x/net from 0.31.0 to 0.32.0
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.31.0 to 0.32.0.
- [Commits](https://github.com/golang/net/compare/v0.31.0...v0.32.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-12-06 00:40:06 +00:00
c44a0c978a Merge pull request #43 from aykhans/dependabot/go_modules/github.com/jedib0t/go-pretty/v6-6.6.3
Bump github.com/jedib0t/go-pretty/v6 from 6.6.2 to 6.6.3
2024-12-01 20:54:09 +04:00
1ace7be2b4 Bump github.com/jedib0t/go-pretty/v6 from 6.6.2 to 6.6.3
Bumps [github.com/jedib0t/go-pretty/v6](https://github.com/jedib0t/go-pretty) from 6.6.2 to 6.6.3.
- [Release notes](https://github.com/jedib0t/go-pretty/releases)
- [Commits](https://github.com/jedib0t/go-pretty/compare/v6.6.2...v6.6.3)

---
updated-dependencies:
- dependency-name: github.com/jedib0t/go-pretty/v6
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-11-29 00:50:11 +00:00
fa55de0cf2 Merge pull request #39 from aykhans/feat/add-proxy-check
Add 'no-proxy-check' parameter
2024-11-28 04:22:12 +04:00
d392d4a787 🔨 Refactor method 'UnmarshalJSON' of 'option[T]' 2024-11-28 04:20:01 +04:00
2e6110e54a 🔥 Remove assets 2024-11-27 01:30:15 +04:00
48721b4ae7 Update README.md 2024-11-27 01:28:07 +04:00
fe4a93b394 🔨 Add constructors to config structs 2024-11-27 00:46:14 +04:00
0725c1a481 🔨 Refactor 'option[T]' type 2024-11-24 16:54:38 +04:00
8d983b4313 🔨 Rename 'IOption' to 'Option' 2024-11-24 02:43:22 +04:00
c69c35bef4 🔨 Replace type 'any' with type 'NonNilConcrete' 2024-11-23 18:16:01 +04:00
e3cbe1e9b4 Merge pull request #42 from aykhans/bump-go-version
🔖 Bump go version '1.22.6 -> 1.23.2'
2024-11-23 18:02:00 +04:00
94211eb018 🔖 Bump go version '1.22.6 -> 1.23.2' 2024-11-23 18:01:03 +04:00
098c1d8cc4 🔨 Make the 'Option' type private and add the 'IOption' type 2024-11-23 17:53:11 +04:00
20 changed files with 566 additions and 335 deletions

View File

@ -1,4 +1,4 @@
FROM golang:1.22.6-alpine AS builder
FROM golang:1.23.2-alpine AS builder
WORKDIR /dodo

View File

@ -1,6 +1,6 @@
<h1 align="center">Dodo is a simple and easy-to-use HTTP benchmarking tool.</h1>
<p align="center">
<img width="30%" height="30%" src="https://raw.githubusercontent.com/aykhans/dodo/main/assets/dodo.png">
<img width="30%" height="30%" src="https://ftp.aykhans.me/web/client/pubshares/hB6VSdCnBCr8gFPeiMuCji/browse?path=%2Fdodo.png">
</p>
## Installation
@ -49,7 +49,7 @@ dodo -u https://example.com -m GET -d 10 -r 1000 -t 2000
```
With Docker:
```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
@ -60,12 +60,12 @@ You can find an example config structure in the [config.json](https://github.com
"url": "https://example.com",
"no_proxy_check": false,
"timeout": 2000,
"dodos_count": 10,
"request_count": 1000,
"dodos": 10,
"requests": 1000,
"params": {},
"headers": {},
"cookies": {},
"body": [""],
"body": [],
"proxies": [
{
"url": "http://example.com:8080",
@ -85,7 +85,7 @@ dodo -c /path/config.json
```
With Docker:
```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)
@ -96,7 +96,7 @@ dodo -c /path/config.json -u https://example.com -m GET -d 10 -r 1000 -t 2000
```
With Docker:
```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
@ -108,8 +108,8 @@ If the Headers, Params, Cookies and Body fields have multiple values, each reque
| Yes | - | --yes | -y | Boolean | Answer yes to all questions | false |
| URL | url | --url | -u | String | URL to send the request to | - |
| Method | method | --method | -m | String | HTTP method | GET |
| Request count | request_count | --request-count | -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 |
| Requests | requests | --requests | -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 |
| 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 | - |

Binary file not shown.

Before

Width:  |  Height:  |  Size: 230 KiB

View File

@ -3,12 +3,12 @@
"url": "https://example.com",
"no_proxy_check": false,
"timeout": 10000,
"dodos_count": 50,
"request_count": 1000,
"dodos": 1,
"requests": 1,
"params": {},
"headers": {},
"cookies": {},
"body": [""],
"body": [],
"proxies": [
{
"url": "http://example.com:8080",

View File

@ -1,30 +1,27 @@
package config
import (
"fmt"
"net/url"
"os"
"strings"
"time"
. "github.com/aykhans/dodo/types"
"github.com/aykhans/dodo/utils"
"github.com/jedib0t/go-pretty/v6/table"
)
const (
VERSION string = "0.5.2"
VERSION string = "0.5.502"
DefaultUserAgent string = "Dodo/" + VERSION
ProxyCheckURL string = "https://www.google.com"
DefaultMethod string = "GET"
DefaultTimeout uint32 = 10000 // Milliseconds (10 seconds)
DefaultDodosCount uint = 1
DefaultRequestCount uint = 1000
DefaultRequestCount uint = 1
MaxDodosCountForProxies uint = 20 // Max dodos count for proxy check
)
type IConfig interface {
MergeConfigs(newConfig IConfig) IConfig
}
type RequestConfig struct {
Method string
URL *url.URL
@ -45,31 +42,48 @@ func (config *RequestConfig) Print() {
t.SetOutputMirror(os.Stdout)
t.SetStyle(table.StyleLight)
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.AppendRow(table.Row{"Method", config.Method})
t.AppendSeparator()
t.AppendRow(table.Row{"URL", config.URL})
t.AppendSeparator()
t.AppendRow(table.Row{"Timeout", fmt.Sprintf("%dms", config.Timeout/time.Millisecond)})
t.AppendRow(table.Row{"Timeout", config.Timeout})
t.AppendSeparator()
t.AppendRow(table.Row{"Dodos", config.DodosCount})
t.AppendSeparator()
t.AppendRow(table.Row{"Request", config.RequestCount})
t.AppendRow(table.Row{"Requests", config.RequestCount})
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.AppendRow(table.Row{"Headers", utils.MarshalJSON(config.Headers, 3)})
t.AppendRow(table.Row{"Headers", string(utils.PrettyJSONMarshal(newHeaders, 3, "", " "))})
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.AppendRow(table.Row{"Proxies Count", len(config.Proxies)})
t.AppendRow(table.Row{"Proxies", string(utils.PrettyJSONMarshal(config.Proxies, 3, "", " "))})
t.AppendSeparator()
t.AppendRow(table.Row{"Proxy Check", !config.NoProxyCheck})
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()
}
@ -93,9 +107,29 @@ type Config struct {
Method string `json:"method" validate:"http_method"` // custom validations: http_method
URL string `json:"url" validate:"http_url,required"`
Timeout uint32 `json:"timeout" validate:"gte=1,lte=100000"`
DodosCount uint `json:"dodos_count" validate:"gte=1"`
RequestCount uint `json:"request_count" validation_name:"request-count" validate:"gte=1"`
NoProxyCheck utils.Option[bool] `json:"no_proxy_check"`
DodosCount uint `json:"dodos" validate:"gte=1"`
RequestCount uint `json:"requests" 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) {
@ -133,7 +167,7 @@ func (config *Config) SetDefaults() {
config.RequestCount = DefaultRequestCount
}
if config.NoProxyCheck.IsNone() {
config.NoProxyCheck = utils.NewOption(false)
config.NoProxyCheck = NewOption(false)
}
}
@ -144,7 +178,7 @@ type Proxy struct {
}
type JSONConfig struct {
Config
*Config
Params map[string][]string `json:"params"`
Headers map[string][]string `json:"headers"`
Cookies map[string][]string `json:"cookies"`
@ -152,8 +186,21 @@ type JSONConfig struct {
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) {
config.Config.MergeConfigs(&newConfig.Config)
config.Config.MergeConfigs(newConfig.Config)
if len(newConfig.Params) != 0 {
config.Params = newConfig.Params
}
@ -172,14 +219,27 @@ func (config *JSONConfig) MergeConfigs(newConfig *JSONConfig) {
}
type CLIConfig struct {
Config
Yes bool `json:"yes" validate:"omitempty"`
*Config
Yes Option[bool] `json:"yes" validate:"omitempty"`
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) {
config.Config.MergeConfigs(&newConfig.Config)
config.Config.MergeConfigs(newConfig.Config)
if newConfig.ConfigFile != "" {
config.ConfigFile = newConfig.ConfigFile
}
if !newConfig.Yes.IsNone() {
config.Yes = newConfig.Yes
}
}

View File

@ -19,10 +19,6 @@ func OSErrorFormater(err error) error {
return ErrInvalidFile
}
func CobraErrorFormater(err error) error {
return err
}
func shortenNamespace(namespace string) string {
return namespace[strings.Index(namespace, ".")+1:]
}

19
go.mod
View File

@ -1,14 +1,12 @@
module github.com/aykhans/dodo
go 1.22.6
go 1.23.2
require (
github.com/go-playground/validator/v10 v10.23.0
github.com/jedib0t/go-pretty/v6 v6.6.2
github.com/spf13/cobra v1.8.1
github.com/spf13/pflag v1.0.5
github.com/valyala/fasthttp v1.57.0
golang.org/x/net v0.31.0
github.com/jedib0t/go-pretty/v6 v6.6.5
github.com/valyala/fasthttp v1.58.0
golang.org/x/net v0.33.0
)
require (
@ -16,14 +14,13 @@ require (
github.com/gabriel-vasile/mimetype v1.4.4 // indirect
github.com/go-playground/locales v0.14.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/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
golang.org/x/crypto v0.29.0 // indirect
golang.org/x/sys v0.27.0 // indirect
golang.org/x/term v0.26.0 // indirect
golang.org/x/text v0.20.0 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/term v0.27.0 // indirect
golang.org/x/text v0.21.0 // indirect
)

37
go.sum
View File

@ -1,6 +1,5 @@
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I=
@ -13,10 +12,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
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.23.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
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/jedib0t/go-pretty/v6 v6.6.5 h1:9PgMJOVBedpgYLI56jQRJYqngxYAAzfEUua+3NgSqAo=
github.com/jedib0t/go-pretty/v6 v6.6.5/go.mod h1:Uq/HrbhuFty5WSVNfjpQQe47x16RwVGXIveNGEyGtHs=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
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=
@ -28,29 +25,23 @@ 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.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
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/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
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/fasthttp v1.57.0 h1:Xw8SjWGEP/+wAAgyy5XTvgrWlOD1+TxbbvNADYCm1Tg=
github.com/valyala/fasthttp v1.57.0/go.mod h1:h6ZBaPRlzpZ6O3H5t2gEk1Qi33+TmLvfwgLLp0t9CpE=
github.com/valyala/fasthttp v1.58.0 h1:GGB2dWxSbEprU9j0iMJHgdKYJVDyjrOwF9RE59PbRuE=
github.com/valyala/fasthttp v1.58.0/go.mod h1:SYXvHHaFp7QZHGKSHmoMipInhrI5StHrhDTYVEjK/Kw=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
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.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
golang.org/x/net v0.31.0 h1:68CPQngjLL0r2AlUKiSxtQFKvzRVbnzLwMUn5SzcLHo=
golang.org/x/net v0.31.0/go.mod h1:P4fl1q7dY2hnZFxEk4pPSkDHF+QqjitcnDjUQyMM+pM=
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.26.0 h1:WEQa6V3Gja/BhNxg540hBip/kkaYtRg3cxg4oXSw4AU=
golang.org/x/term v0.26.0/go.mod h1:Si5m1o57C5nBNQo5z1iq+XDijt21BDBDp2bK0QI8e3E=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

24
main.go
View File

@ -21,13 +21,19 @@ import (
func main() {
validator := validation.NewValidator()
conf := config.Config{}
jsonConf := config.JSONConfig{}
conf := config.NewConfig("", 0, 0, 0, nil)
jsonConf := config.NewJSONConfig(
config.NewConfig("", 0, 0, 0, nil), nil, nil, nil, nil, nil,
)
cliConf, err := readers.CLIConfigReader()
if err != nil || cliConf == nil {
if err != nil {
utils.PrintAndExit(err.Error())
}
if cliConf == nil {
os.Exit(0)
}
if err := validator.StructPartial(cliConf, "ConfigFile"); err != nil {
utils.PrintErrAndExit(
customerrors.ValidationErrorsFormater(
@ -51,11 +57,11 @@ func main() {
),
)
}
jsonConf = *jsonConfNew
conf.MergeConfigs(&jsonConf.Config)
jsonConf = jsonConfNew
conf.MergeConfigs(jsonConf.Config)
}
conf.MergeConfigs(&cliConf.Config)
conf.MergeConfigs(cliConf.Config)
conf.SetDefaults()
if err := validator.Struct(conf); err != nil {
utils.PrintErrAndExit(
@ -80,11 +86,11 @@ func main() {
Cookies: jsonConf.Cookies,
Proxies: jsonConf.Proxies,
Body: jsonConf.Body,
Yes: cliConf.Yes,
NoProxyCheck: *conf.NoProxyCheck.ValueOrPanic(),
Yes: cliConf.Yes.ValueOr(false),
NoProxyCheck: conf.NoProxyCheck.ValueOr(false),
}
requestConf.Print()
if !cliConf.Yes {
if !cliConf.Yes.ValueOr(false) {
response := readers.CLIYesOrNoReader("Do you want to continue?", true)
if !response {
utils.PrintAndExit("Exiting...")

View File

@ -1,73 +1,128 @@
package readers
import (
"flag"
"fmt"
"strings"
"github.com/aykhans/dodo/config"
"github.com/aykhans/dodo/custom_errors"
. "github.com/aykhans/dodo/types"
"github.com/aykhans/dodo/utils"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func CLIConfigReader() (*config.CLIConfig, error) {
var (
returnNil = false
cliConfig = &config.CLIConfig{
Config: config.Config{
NoProxyCheck: utils.NewNoneOption[bool](),
},
}
dodosCount uint
requestCount uint
timeout uint32
noProxyCheck bool
rootCmd = &cobra.Command{
Use: "dodo [flags]",
Example: ` Simple usage only with URL:
const usageText = `Usage:
dodo [flags]
Examples:
Simple usage only with URL:
dodo -u https://example.com
Simple usage with config file:
Simple usage with config file:
dodo -c /path/to/config/file/config.json
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`,
Run: func(cmd *cobra.Command, args []string) {},
SilenceErrors: true,
SilenceUsage: true,
Version: config.VERSION,
}
)
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
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")
rootCmd.Flags().BoolVar(&noProxyCheck, "no-proxy-check", false, "Do not check for proxies")
if err := rootCmd.Execute(); err != nil {
utils.PrintErr(err)
rootCmd.Println(rootCmd.UsageString())
return nil, customerrors.CobraErrorFormater(err)
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)
-y, --yes bool Answer yes to all questions (default false)`
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 {
case "help":
case "version", "v":
fmt.Printf("dodo version %s\n", config.VERSION)
returnNil = true
case "version":
returnNil = true
case "dodos-count":
case "config-file", "c":
cliConfig.ConfigFile = configFile
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
case "request-count":
cliConfig.RequestCount = requestCount
case "timeout":
cliConfig.Timeout = timeout
case "requests", "r":
cliConfig.RequestCount = requestsCount
case "timeout", "t":
var maxUint32 uint = 4294967295
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 = utils.NewOption(noProxyCheck)
cliConfig.NoProxyCheck.SetValue(noProxyCheck)
}
})
if returnNil {
return nil, nil
}

View File

@ -6,7 +6,6 @@ import (
"github.com/aykhans/dodo/config"
customerrors "github.com/aykhans/dodo/custom_errors"
"github.com/aykhans/dodo/utils"
)
func JSONConfigReader(filePath string) (*config.JSONConfig, error) {
@ -14,11 +13,10 @@ func JSONConfigReader(filePath string) (*config.JSONConfig, error) {
if err != nil {
return nil, customerrors.OSErrorFormater(err)
}
jsonConf := &config.JSONConfig{
Config: config.Config{
NoProxyCheck: utils.NewNoneOption[bool](),
},
}
jsonConf := config.NewJSONConfig(
config.NewConfig("", 0, 0, 0, nil),
nil, nil, nil, nil, nil,
)
err = json.Unmarshal(data, &jsonConf)
if err != nil {

View File

@ -1,85 +1,108 @@
package requests
import (
"fmt"
"os"
"time"
. "github.com/aykhans/dodo/types"
"github.com/aykhans/dodo/utils"
"github.com/jedib0t/go-pretty/v6/table"
)
type Response struct {
StatusCode int
Error error
Response string
Time time.Duration
}
type Responses []*Response
// Print prints the responses in a tabular format, including information such as
// response count, minimum time, maximum time, and average time.
func (respones Responses) Print() {
var (
totalMinDuration time.Duration = respones[0].Time
totalMaxDuration time.Duration = respones[0].Time
totalDuration time.Duration
totalCount int = len(respones)
)
mergedResponses := make(map[string][]time.Duration)
for _, response := range respones {
if response.Time < totalMinDuration {
totalMinDuration = response.Time
// response count, minimum time, maximum time, average time, and latency percentiles.
func (responses Responses) Print() {
total := struct {
Count int
Min time.Duration
Max time.Duration
Sum time.Duration
P90 time.Duration
P95 time.Duration
P99 time.Duration
}{
Count: len(responses),
Min: responses[0].Time,
Max: responses[0].Time,
}
if response.Time > totalMaxDuration {
totalMaxDuration = response.Time
}
totalDuration += response.Time
mergedResponses := make(map[string]Durations)
var allDurations Durations
if response.Error != nil {
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)],
for _, response := range responses {
if response.Time < total.Min {
total.Min = response.Time
}
if response.Time > total.Max {
total.Max = response.Time
}
total.Sum += response.Time
mergedResponses[response.Response] = append(
mergedResponses[response.Response],
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.SetOutputMirror(os.Stdout)
t.SetStyle(table.StyleLight)
t.SetColumnConfigs([]table.ColumnConfig{
{Number: 1, WidthMax: 80},
{Number: 1, WidthMax: 40},
})
t.AppendHeader(table.Row{
"Response",
"Count",
"Min Time",
"Max Time",
"Average Time",
"Min",
"Max",
"Average",
"P90",
"P95",
"P99",
})
var roundPrecision int64 = 4
for key, durations := range mergedResponses {
durations.Sort()
durationsLen := len(durations)
durationsLenAsFloat := float64(durationsLen - 1)
t.AppendRow(table.Row{
key,
len(durations),
utils.MinDuration(durations...),
utils.MaxDuration(durations...),
utils.AvgDuration(durations...),
durationsLen,
utils.DurationRoundBy(*durations.First(), roundPrecision),
utils.DurationRoundBy(*durations.Last(), roundPrecision),
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()
}
if len(mergedResponses) > 1 {
t.AppendRow(table.Row{
"Total",
totalCount,
totalMinDuration,
totalMaxDuration,
totalDuration / time.Duration(totalCount),
total.Count,
utils.DurationRoundBy(total.Min, roundPrecision),
utils.DurationRoundBy(total.Max, roundPrecision),
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()
}

View File

@ -2,6 +2,7 @@ package requests
import (
"context"
"strconv"
"sync"
"time"
@ -142,8 +143,7 @@ func sendRequest(
return
}
*responseData = append(*responseData, &Response{
StatusCode: 0,
Error: err,
Response: err.Error(),
Time: completedTime,
})
increase <- 1
@ -151,8 +151,7 @@ func sendRequest(
}
*responseData = append(*responseData, &Response{
StatusCode: response.StatusCode(),
Error: nil,
Response: strconv.Itoa(response.StatusCode()),
Time: completedTime,
})
increase <- 1

41
types/durations.go Normal file
View 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))
}

89
types/option.go Normal file
View File

@ -0,0 +1,89 @@
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}
}

View File

@ -6,49 +6,80 @@ import (
"reflect"
)
func MarshalJSON(v any, maxSliceSize uint) string {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Slice && rv.Len() == 0 {
return "[]"
}
data, err := json.MarshalIndent(truncateLists(v, int(maxSliceSize)), "", " ")
if err != nil {
return "{}"
}
return string(data)
type TruncatedMarshaller struct {
Value interface{}
MaxItems int
}
func truncateLists(v interface{}, maxItems int) interface{} {
rv := reflect.ValueOf(v)
func (t TruncatedMarshaller) MarshalJSON() ([]byte, error) {
val := reflect.ValueOf(t.Value)
switch rv.Kind() {
case reflect.Slice, reflect.Array:
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()
if val.Kind() != reflect.Slice && val.Kind() != reflect.Array {
return json.Marshal(t.Value)
}
if val.Len() == 0 {
return []byte("[]"), nil
}
length := val.Len()
if length <= t.MaxItems {
return json.Marshal(t.Value)
}
truncated := make([]interface{}, t.MaxItems+1)
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 := 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:
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)
newMap := make(map[string]interface{})
iter := val.MapRange()
for iter.Next() {
k := iter.Key().String()
newMap[k] = processValue(iter.Value().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
}
}

21
utils/int.go Normal file
View 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
}

View File

@ -2,30 +2,13 @@ package utils
import "time"
func MinDuration(durations ...time.Duration) time.Duration {
min := durations[0]
for _, d := range durations {
if d < min {
min = d
func DurationRoundBy(duration time.Duration, n int64) time.Duration {
if durationLen := NumLen(duration.Nanoseconds()); durationLen > n {
roundNum := 1
for range durationLen - n {
roundNum *= 10
}
return duration.Round(time.Duration(roundNum))
}
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))
return duration
}

View File

@ -1,59 +0,0 @@
package utils
import (
"encoding/json"
"errors"
)
// Don't call this struct directly, use NewOption[T] or NewNoneOption[T] instead.
type Option[T any] 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
}
// The returned value can be nil, if the Option is None, it will return nil and an error.
func (o *Option[T]) ValueOrErr() (*T, error) {
if o.IsNone() {
return nil, errors.New("Option is None")
}
return &o.value, nil
}
// The returned value can't be 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
}
// The returned value can't be nil, 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]) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
o.none = true
return nil
}
o.none = false
return json.Unmarshal(data, &o.value)
}
func NewOption[T any](value T) Option[T] {
return Option[T]{value: value}
}
func NewNoneOption[T any]() Option[T] {
return Option[T]{none: true}
}