mirror of
https://github.com/aykhans/dodo.git
synced 2025-07-01 16:07:49 +00:00
Compare commits
20 Commits
Author | SHA1 | Date | |
---|---|---|---|
779d5e9b18 | |||
6a79d0b1d7 | |||
1e53b8a7fb | |||
0a8dbec739 | |||
3762890914 | |||
ca6b3d4eb2 | |||
1ee06aacc3 | |||
3d5834a6a6 | |||
f1521cbb74 | |||
40f8a1cc37 | |||
8a3574cd48 | |||
5a2a4c47b2 | |||
ff09a3365e | |||
c83246abe4 | |||
efc4c62001 | |||
f567774e3a | |||
d2bd60e3ff | |||
0fe782c768 | |||
b9dd14a588 | |||
18b1c7dae3 |
10
README.md
10
README.md
@ -59,9 +59,9 @@ 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,
|
"no_proxy_check": false,
|
||||||
"timeout": 10000,
|
"timeout": 2000,
|
||||||
"dodos_count": 1,
|
"dodos": 10,
|
||||||
"request_count": 1,
|
"requests": 1000,
|
||||||
"params": {},
|
"params": {},
|
||||||
"headers": {},
|
"headers": {},
|
||||||
"cookies": {},
|
"cookies": {},
|
||||||
@ -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 |
|
| Yes | - | --yes | -y | Boolean | Answer yes to all questions | false |
|
||||||
| URL | url | --url | -u | String | URL to send the request to | - |
|
| URL | url | --url | -u | String | URL to send the request to | - |
|
||||||
| Method | method | --method | -m | String | HTTP method | GET |
|
| Method | method | --method | -m | String | HTTP method | GET |
|
||||||
| Request count | request_count | --request-count | -r | Integer | Total number of requests to send | 1000 |
|
| Requests | requests | --requests | -r | Integer | Total number of requests to send | 1000 |
|
||||||
| Dodos count (Threads) | dodos_count | --dodos-count | -d | Integer | Number of dodos (threads) to send requests in parallel | 1 |
|
| Dodos (Threads) | dodos | --dodos | -d | Integer | Number of dodos (threads) to send requests in parallel | 1 |
|
||||||
| Timeout | timeout | --timeout | -t | Integer | Timeout for canceling each request (milliseconds) | 10000 |
|
| Timeout | timeout | --timeout | -t | Integer | Timeout for canceling each request (milliseconds) | 10000 |
|
||||||
| No Proxy Check | no_proxy_check | --no-proxy-check| - | Boolean | Disable proxy check | false |
|
| No Proxy Check | no_proxy_check | --no-proxy-check| - | Boolean | Disable proxy check | false |
|
||||||
| Params | params | - | - | Key-Value {String: [String]} | Request parameters | - |
|
| Params | params | - | - | Key-Value {String: [String]} | Request parameters | - |
|
||||||
|
@ -3,8 +3,8 @@
|
|||||||
"url": "https://example.com",
|
"url": "https://example.com",
|
||||||
"no_proxy_check": false,
|
"no_proxy_check": false,
|
||||||
"timeout": 10000,
|
"timeout": 10000,
|
||||||
"dodos_count": 1,
|
"dodos": 1,
|
||||||
"request_count": 1,
|
"requests": 1,
|
||||||
"params": {},
|
"params": {},
|
||||||
"headers": {},
|
"headers": {},
|
||||||
"cookies": {},
|
"cookies": {},
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
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/types"
|
||||||
@ -12,7 +12,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
VERSION string = "0.5.4"
|
VERSION string = "0.5.502"
|
||||||
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"
|
||||||
@ -42,7 +42,18 @@ func (config *RequestConfig) Print() {
|
|||||||
t.SetOutputMirror(os.Stdout)
|
t.SetOutputMirror(os.Stdout)
|
||||||
t.SetStyle(table.StyleLight)
|
t.SetStyle(table.StyleLight)
|
||||||
t.SetColumnConfigs([]table.ColumnConfig{
|
t.SetColumnConfigs([]table.ColumnConfig{
|
||||||
{Number: 2, WidthMax: 50},
|
{
|
||||||
|
Number: 2,
|
||||||
|
WidthMaxEnforcer: func(col string, maxLen int) string {
|
||||||
|
lines := strings.Split(col, "\n")
|
||||||
|
for i, line := range lines {
|
||||||
|
if len(line) > maxLen {
|
||||||
|
lines[i] = line[:maxLen-3] + "..."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
},
|
||||||
|
WidthMax: 50},
|
||||||
})
|
})
|
||||||
|
|
||||||
newHeaders := make(map[string][]string)
|
newHeaders := make(map[string][]string)
|
||||||
@ -56,23 +67,23 @@ func (config *RequestConfig) Print() {
|
|||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"URL", config.URL})
|
t.AppendRow(table.Row{"URL", config.URL})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Timeout", fmt.Sprintf("%dms", config.Timeout/time.Millisecond)})
|
t.AppendRow(table.Row{"Timeout", config.Timeout})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Dodos", config.DodosCount})
|
t.AppendRow(table.Row{"Dodos", config.DodosCount})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Requests", config.RequestCount})
|
t.AppendRow(table.Row{"Requests", config.RequestCount})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Params", utils.MarshalJSON(config.Params, 3)})
|
t.AppendRow(table.Row{"Params", string(utils.PrettyJSONMarshal(config.Params, 3, "", " "))})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Headers", utils.MarshalJSON(newHeaders, 3)})
|
t.AppendRow(table.Row{"Headers", string(utils.PrettyJSONMarshal(newHeaders, 3, "", " "))})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Cookies", utils.MarshalJSON(config.Cookies, 3)})
|
t.AppendRow(table.Row{"Cookies", string(utils.PrettyJSONMarshal(config.Cookies, 3, "", " "))})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Proxies Count", len(config.Proxies)})
|
t.AppendRow(table.Row{"Proxies", string(utils.PrettyJSONMarshal(config.Proxies, 3, "", " "))})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Proxy Check", !config.NoProxyCheck})
|
t.AppendRow(table.Row{"Proxy Check", !config.NoProxyCheck})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Body", utils.MarshalJSON(config.Body, 3)})
|
t.AppendRow(table.Row{"Body", string(utils.PrettyJSONMarshal(config.Body, 3, "", " "))})
|
||||||
|
|
||||||
t.Render()
|
t.Render()
|
||||||
}
|
}
|
||||||
@ -96,8 +107,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_count" validate:"gte=1"`
|
DodosCount uint `json:"dodos" validate:"gte=1"`
|
||||||
RequestCount uint `json:"request_count" validation_name:"request-count" validate:"gte=1"`
|
RequestCount uint `json:"requests" validation_name:"request-count" validate:"gte=1"`
|
||||||
NoProxyCheck Option[bool] `json:"no_proxy_check"`
|
NoProxyCheck Option[bool] `json:"no_proxy_check"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -209,8 +220,8 @@ func (config *JSONConfig) MergeConfigs(newConfig *JSONConfig) {
|
|||||||
|
|
||||||
type CLIConfig struct {
|
type CLIConfig struct {
|
||||||
*Config
|
*Config
|
||||||
Yes Option[bool] `json:"yes" validate:"omitempty"`
|
Yes Option[bool] `json:"yes" validate:"omitempty"`
|
||||||
ConfigFile string `validation_name:"config-file" validate:"omitempty,filepath"`
|
ConfigFile string `validation_name:"config-file" validate:"omitempty,filepath"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCLIConfig(
|
func NewCLIConfig(
|
||||||
|
2
go.mod
2
go.mod
@ -6,7 +6,7 @@ require (
|
|||||||
github.com/go-playground/validator/v10 v10.23.0
|
github.com/go-playground/validator/v10 v10.23.0
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.5
|
github.com/jedib0t/go-pretty/v6 v6.6.5
|
||||||
github.com/valyala/fasthttp v1.58.0
|
github.com/valyala/fasthttp v1.58.0
|
||||||
golang.org/x/net v0.32.0
|
golang.org/x/net v0.33.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
4
go.sum
4
go.sum
@ -35,8 +35,8 @@ github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZ
|
|||||||
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.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
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/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||||
golang.org/x/net v0.32.0 h1:ZqPmj8Kzc+Y6e0+skZsuACbx+wzMgo5MQsJh9Qd6aYI=
|
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
||||||
golang.org/x/net v0.32.0/go.mod h1:CwU0IoeOlnQQWJ6ioyFrfRuomB8GKF6KbYXZVyeXNfs=
|
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 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
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 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q=
|
||||||
|
@ -28,9 +28,9 @@ Flags:
|
|||||||
-h, --help help for dodo
|
-h, --help help for dodo
|
||||||
-v, --version version for dodo
|
-v, --version version for dodo
|
||||||
-c, --config-file string Path to the config file
|
-c, --config-file string Path to the config file
|
||||||
-d, --dodos-count uint Number of dodos(threads) (default %d)
|
-d, --dodos uint Number of dodos(threads) (default %d)
|
||||||
-m, --method string HTTP Method (default %s)
|
-m, --method string HTTP Method (default %s)
|
||||||
-r, --request-count uint Number of total requests (default %d)
|
-r, --request uint Number of total requests (default %d)
|
||||||
-t, --timeout uint32 Timeout for each request in milliseconds (default %d)
|
-t, --timeout uint32 Timeout for each request in milliseconds (default %d)
|
||||||
-u, --url string URL for stress testing
|
-u, --url string URL for stress testing
|
||||||
--no-proxy-check bool Do not check for proxies (default false)
|
--no-proxy-check bool Do not check for proxies (default false)
|
||||||
@ -74,10 +74,10 @@ func CLIConfigReader() (*config.CLIConfig, error) {
|
|||||||
flag.StringVar(&url, "url", "", "URL to send the request")
|
flag.StringVar(&url, "url", "", "URL to send the request")
|
||||||
flag.StringVar(&url, "u", "", "URL to send the request")
|
flag.StringVar(&url, "u", "", "URL to send the request")
|
||||||
|
|
||||||
flag.UintVar(&dodosCount, "dodos-count", 0, "Number of dodos(threads)")
|
flag.UintVar(&dodosCount, "dodos", 0, "Number of dodos(threads)")
|
||||||
flag.UintVar(&dodosCount, "d", 0, "Number of dodos(threads)")
|
flag.UintVar(&dodosCount, "d", 0, "Number of dodos(threads)")
|
||||||
|
|
||||||
flag.UintVar(&requestsCount, "requests-count", 0, "Number of total requests")
|
flag.UintVar(&requestsCount, "requests", 0, "Number of total requests")
|
||||||
flag.UintVar(&requestsCount, "r", 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, "timeout", 0, "Timeout for each request in milliseconds")
|
||||||
@ -107,9 +107,9 @@ func CLIConfigReader() (*config.CLIConfig, error) {
|
|||||||
cliConfig.Method = method
|
cliConfig.Method = method
|
||||||
case "url", "u":
|
case "url", "u":
|
||||||
cliConfig.URL = url
|
cliConfig.URL = url
|
||||||
case "dodos-count", "d":
|
case "dodos", "d":
|
||||||
cliConfig.DodosCount = dodosCount
|
cliConfig.DodosCount = dodosCount
|
||||||
case "requests-count", "r":
|
case "requests", "r":
|
||||||
cliConfig.RequestCount = requestsCount
|
cliConfig.RequestCount = requestsCount
|
||||||
case "timeout", "t":
|
case "timeout", "t":
|
||||||
var maxUint32 uint = 4294967295
|
var maxUint32 uint = 4294967295
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
. "github.com/aykhans/dodo/types"
|
. "github.com/aykhans/dodo/types"
|
||||||
|
"github.com/aykhans/dodo/utils"
|
||||||
"github.com/jedib0t/go-pretty/v6/table"
|
"github.com/jedib0t/go-pretty/v6/table"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -17,7 +18,7 @@ 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, average time, and latency percentiles.
|
||||||
func (respones Responses) Print() {
|
func (responses Responses) Print() {
|
||||||
total := struct {
|
total := struct {
|
||||||
Count int
|
Count int
|
||||||
Min time.Duration
|
Min time.Duration
|
||||||
@ -27,14 +28,14 @@ func (respones Responses) Print() {
|
|||||||
P95 time.Duration
|
P95 time.Duration
|
||||||
P99 time.Duration
|
P99 time.Duration
|
||||||
}{
|
}{
|
||||||
Count: len(respones),
|
Count: len(responses),
|
||||||
Min: respones[0].Time,
|
Min: responses[0].Time,
|
||||||
Max: respones[0].Time,
|
Max: responses[0].Time,
|
||||||
}
|
}
|
||||||
mergedResponses := make(map[string]Durations)
|
mergedResponses := make(map[string]Durations)
|
||||||
var allDurations Durations
|
var allDurations Durations
|
||||||
|
|
||||||
for _, response := range respones {
|
for _, response := range responses {
|
||||||
if response.Time < total.Min {
|
if response.Time < total.Min {
|
||||||
total.Min = response.Time
|
total.Min = response.Time
|
||||||
}
|
}
|
||||||
@ -64,14 +65,15 @@ func (respones Responses) Print() {
|
|||||||
t.AppendHeader(table.Row{
|
t.AppendHeader(table.Row{
|
||||||
"Response",
|
"Response",
|
||||||
"Count",
|
"Count",
|
||||||
"Min Time",
|
"Min",
|
||||||
"Max Time",
|
"Max",
|
||||||
"Average Time",
|
"Average",
|
||||||
"P90",
|
"P90",
|
||||||
"P95",
|
"P95",
|
||||||
"P99",
|
"P99",
|
||||||
})
|
})
|
||||||
|
|
||||||
|
var roundPrecision int64 = 4
|
||||||
for key, durations := range mergedResponses {
|
for key, durations := range mergedResponses {
|
||||||
durations.Sort()
|
durations.Sort()
|
||||||
durationsLen := len(durations)
|
durationsLen := len(durations)
|
||||||
@ -80,12 +82,12 @@ func (respones Responses) Print() {
|
|||||||
t.AppendRow(table.Row{
|
t.AppendRow(table.Row{
|
||||||
key,
|
key,
|
||||||
durationsLen,
|
durationsLen,
|
||||||
durations.First(),
|
utils.DurationRoundBy(*durations.First(), roundPrecision),
|
||||||
durations.Last(),
|
utils.DurationRoundBy(*durations.Last(), roundPrecision),
|
||||||
durations.Avg(),
|
utils.DurationRoundBy(durations.Avg(), roundPrecision),
|
||||||
durations[int(0.90*durationsLenAsFloat)],
|
utils.DurationRoundBy(durations[int(0.90*durationsLenAsFloat)], roundPrecision),
|
||||||
durations[int(0.95*durationsLenAsFloat)],
|
utils.DurationRoundBy(durations[int(0.95*durationsLenAsFloat)], roundPrecision),
|
||||||
durations[int(0.99*durationsLenAsFloat)],
|
utils.DurationRoundBy(durations[int(0.99*durationsLenAsFloat)], roundPrecision),
|
||||||
})
|
})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
}
|
}
|
||||||
@ -94,12 +96,12 @@ func (respones Responses) Print() {
|
|||||||
t.AppendRow(table.Row{
|
t.AppendRow(table.Row{
|
||||||
"Total",
|
"Total",
|
||||||
total.Count,
|
total.Count,
|
||||||
total.Min,
|
utils.DurationRoundBy(total.Min, roundPrecision),
|
||||||
total.Max,
|
utils.DurationRoundBy(total.Max, roundPrecision),
|
||||||
total.Sum / time.Duration(total.Count), // Average
|
utils.DurationRoundBy(total.Sum/time.Duration(total.Count), roundPrecision), // Average
|
||||||
total.P90,
|
utils.DurationRoundBy(total.P90, roundPrecision),
|
||||||
total.P95,
|
utils.DurationRoundBy(total.P95, roundPrecision),
|
||||||
total.P99,
|
utils.DurationRoundBy(total.P99, roundPrecision),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
t.Render()
|
t.Render()
|
||||||
|
109
utils/convert.go
109
utils/convert.go
@ -6,49 +6,80 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
)
|
)
|
||||||
|
|
||||||
func MarshalJSON(v any, maxSliceSize uint) string {
|
type TruncatedMarshaller struct {
|
||||||
rv := reflect.ValueOf(v)
|
Value interface{}
|
||||||
if rv.Kind() == reflect.Slice && rv.Len() == 0 {
|
MaxItems int
|
||||||
return "[]"
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := json.MarshalIndent(truncateLists(v, int(maxSliceSize)), "", " ")
|
|
||||||
if err != nil {
|
|
||||||
return "{}"
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(data)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func truncateLists(v interface{}, maxItems int) interface{} {
|
func (t TruncatedMarshaller) MarshalJSON() ([]byte, error) {
|
||||||
rv := reflect.ValueOf(v)
|
val := reflect.ValueOf(t.Value)
|
||||||
|
|
||||||
switch rv.Kind() {
|
if val.Kind() != reflect.Slice && val.Kind() != reflect.Array {
|
||||||
case reflect.Slice, reflect.Array:
|
return json.Marshal(t.Value)
|
||||||
if rv.Len() > maxItems {
|
}
|
||||||
newSlice := reflect.MakeSlice(rv.Type(), maxItems, maxItems)
|
if val.Len() == 0 {
|
||||||
reflect.Copy(newSlice, rv.Slice(0, maxItems))
|
return []byte("[]"), nil
|
||||||
newSlice = reflect.Append(newSlice, reflect.ValueOf(fmt.Sprintf("...(%d more)", rv.Len()-maxItems)))
|
}
|
||||||
return newSlice.Interface()
|
|
||||||
}
|
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:
|
case reflect.Map:
|
||||||
newMap := reflect.MakeMap(rv.Type())
|
newMap := make(map[string]interface{})
|
||||||
for _, key := range rv.MapKeys() {
|
iter := val.MapRange()
|
||||||
newMap.SetMapIndex(key, reflect.ValueOf(truncateLists(rv.MapIndex(key).Interface(), maxItems)))
|
for iter.Next() {
|
||||||
|
k := iter.Key().String()
|
||||||
|
newMap[k] = processValue(iter.Value().Interface(), maxItems)
|
||||||
}
|
}
|
||||||
return newMap.Interface()
|
return newMap
|
||||||
case reflect.Struct:
|
|
||||||
newStruct := reflect.New(rv.Type()).Elem()
|
|
||||||
for i := 0; i < rv.NumField(); i++ {
|
|
||||||
newStruct.Field(i).Set(reflect.ValueOf(truncateLists(rv.Field(i).Interface(), maxItems)))
|
|
||||||
}
|
|
||||||
return newStruct.Interface()
|
|
||||||
case reflect.Ptr:
|
|
||||||
if rv.IsNil() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return truncateLists(rv.Elem().Interface(), maxItems)
|
|
||||||
}
|
|
||||||
|
|
||||||
return v
|
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
21
utils/int.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
type Number interface {
|
||||||
|
int | int8 | int16 | int32 | int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NumLen[T Number](n T) T {
|
||||||
|
if n < 0 {
|
||||||
|
n = -n
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
var count T = 0
|
||||||
|
for n > 0 {
|
||||||
|
n /= 10
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
14
utils/time.go
Normal file
14
utils/time.go
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
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 duration
|
||||||
|
}
|
Reference in New Issue
Block a user