Merge pull request #101 from aykhans/feat/add-duration
All checks were successful
golangci-lint / lint (push) Successful in 23s

 Add duration
This commit is contained in:
Aykhan Shahsuvarov 2025-03-24 18:12:10 +04:00 committed by GitHub
commit 7e05cf4f6b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 239 additions and 77 deletions

View File

@ -6,15 +6,15 @@
## Table of Contents ## Table of Contents
- [Installation](#installation) - [Installation](#installation)
- [Using Docker (Recommended)](#using-docker-recommended) - [Using Docker (Recommended)](#using-docker-recommended)
- [Using Pre-built Binaries](#using-pre-built-binaries) - [Using Pre-built Binaries](#using-pre-built-binaries)
- [Building from Source](#building-from-source) - [Building from Source](#building-from-source)
- [Usage](#usage) - [Usage](#usage)
- [1. CLI Usage](#1-cli-usage) - [1. CLI Usage](#1-cli-usage)
- [2. Config File Usage](#2-config-file-usage) - [2. Config File Usage](#2-config-file-usage)
- [2.1 JSON Example](#21-json-example) - [2.1 JSON Example](#21-json-example)
- [2.2 YAML/YML Example](#22-yamlyml-example) - [2.2 YAML/YML Example](#22-yamlyml-example)
- [3. CLI & Config File Combination](#3-cli--config-file-combination) - [3. CLI & Config File Combination](#3-cli--config-file-combination)
- [Config Parameters Reference](#config-parameters-reference) - [Config Parameters Reference](#config-parameters-reference)
## Installation ## Installation
@ -46,6 +46,7 @@ Download the latest binaries from the [releases](https://github.com/aykhans/dodo
### Building from Source ### Building from Source
To build Dodo from source, ensure you have [Go 1.24+](https://golang.org/dl/) installed. To build Dodo from source, ensure you have [Go 1.24+](https://golang.org/dl/) installed.
```sh ```sh
go install -ldflags "-s -w" github.com/aykhans/dodo@latest go install -ldflags "-s -w" github.com/aykhans/dodo@latest
``` ```
@ -56,21 +57,21 @@ Dodo supports CLI arguments, configuration files (JSON/YAML), or a combination o
### 1. CLI Usage ### 1. CLI Usage
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 2 seconds: Send 1000 GET requests to https://example.com with 10 parallel dodos (threads), each with a timeout of 2 seconds, within a maximum duration of 1 minute:
```sh ```sh
dodo -u https://example.com -m GET -d 10 -r 1000 -t 2s dodo -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 2s
``` ```
With Docker: With Docker:
```sh ```sh
docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2s docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 2s
``` ```
### 2. Config File Usage ### 2. Config File Usage
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 800 milliseconds: Send 1000 GET requests to https://example.com with 10 parallel dodos (threads), each with a timeout of 800 milliseconds, within a maximum duration of 250 seconds:
#### 2.1 JSON Example #### 2.1 JSON Example
@ -82,6 +83,7 @@ Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) a
"timeout": "800ms", "timeout": "800ms",
"dodos": 10, "dodos": 10,
"requests": 1000, "requests": 1000,
"duration": "250s",
"params": [ "params": [
// A random value will be selected from the list for first "key1" param on each request // A random value will be selected from the list for first "key1" param on each request
@ -159,6 +161,7 @@ yes: false
timeout: "800ms" timeout: "800ms"
dodos: 10 dodos: 10
requests: 1000 requests: 1000
duration: "250s"
params: params:
# A random value will be selected from the list for first "key1" param on each request # A random value will be selected from the list for first "key1" param on each request
@ -230,30 +233,31 @@ docker run --rm -i aykhans/dodo -f https://example.com/config.yaml
CLI arguments override config file values: CLI arguments override config file values:
```sh ```sh
dodo -f /path/to/config.yaml -u https://example.com -m GET -d 10 -r 1000 -t 5s dodo -f /path/to/config.yaml -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 5s
``` ```
With Docker: With Docker:
```sh ```sh
docker run --rm -i -v /path/to/config.json:/config.json aykhans/dodo -f /config.json -u https://example.com -m GET -d 10 -r 1000 -t 5s docker run --rm -i -v /path/to/config.json:/config.json aykhans/dodo -f /config.json -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 5s
``` ```
## Config Parameters Reference ## Config Parameters Reference
If `Headers`, `Params`, `Cookies`, `Body`, or `Proxy` fields have multiple values, each request will choose a random value from the list. If `Headers`, `Params`, `Cookies`, `Body`, or `Proxy` fields have multiple values, each request will choose a random value from the list.
| Parameter | JSON config file | CLI Flag | CLI Short Flag | Type | Description | Default | | Parameter | config file | CLI Flag | CLI Short Flag | Type | Description | Default |
| --------------- | ---------------- | ------------ | -------------- | ------------------------------ | --------------------------------------------------------------- | ------- | | --------------- | ----------- | ------------ | -------------- | ------------------------------ | ----------------------------------------------------------- | ------- |
| Config file | - | -config-file | -f | String | Path to local config file or http(s) URL of the config file | - | | Config file | - | -config-file | -f | String | Path to local config file or http(s) URL of the config file | - |
| Yes | yes | -yes | -y | Boolean | Answer yes to all questions | false | | Yes | yes | -yes | -y | Boolean | Answer yes to all questions | false |
| URL | url | -url | -u | String | URL to send the request to | - | | URL | url | -url | -u | String | URL to send the request to | - |
| Method | method | -method | -m | String | HTTP method | GET | | Method | method | -method | -m | String | HTTP method | GET |
| Requests | requests | -requests | -r | UnsignedInteger | Total number of requests to send | 1000 | | Dodos (Threads) | dodos | -dodos | -d | UnsignedInteger | Number of dodos (threads) to send requests in parallel | 1 |
| Dodos (Threads) | dodos | -dodos | -d | UnsignedInteger | Number of dodos (threads) to send requests in parallel | 1 | | Requests | requests | -requests | -r | UnsignedInteger | Total number of requests to send | - |
| Timeout | timeout | -timeout | -t | Duration | Timeout for canceling each request | 10s | | Duration | duration | -duration | -o | Time | Maximum duration for the test | - |
| Params | params | -param | -p | [{String: String OR [String]}] | Request parameters | - | | Timeout | timeout | -timeout | -t | Time | Timeout for canceling each request | 10s |
| Headers | headers | -header | -H | [{String: String OR [String]}] | Request headers | - | | Params | params | -param | -p | [{String: String OR [String]}] | Request parameters | - |
| Cookies | cookies | -cookie | -c | [{String: String OR [String]}] | Request cookies | - | | Headers | headers | -header | -H | [{String: String OR [String]}] | Request headers | - |
| Body | body | -body | -b | String OR [String] | Request body or list of request bodies | - | | Cookies | cookies | -cookie | -c | [{String: String OR [String]}] | Request cookies | - |
| Proxy | proxies | -proxy | -x | String OR [String] | Proxy URL or list of proxy URLs | - | | Body | body | -body | -b | String OR [String] | Request body or list of request bodies | - |
| Proxy | proxies | -proxy | -x | String OR [String] | Proxy URL or list of proxy URLs | - |

View File

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

View File

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

View File

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

View File

@ -15,12 +15,13 @@ import (
) )
const ( const (
VERSION string = "0.6.1" VERSION string = "0.6.2"
DefaultUserAgent string = "Dodo/" + VERSION DefaultUserAgent string = "Dodo/" + VERSION
DefaultMethod string = "GET" DefaultMethod string = "GET"
DefaultTimeout time.Duration = time.Second * 10 DefaultTimeout time.Duration = time.Second * 10
DefaultDodosCount uint = 1 DefaultDodosCount uint = 1
DefaultRequestCount uint = 1 DefaultRequestCount uint = 0
DefaultDuration time.Duration = 0
DefaultYes bool = false DefaultYes bool = false
) )
@ -32,6 +33,7 @@ type RequestConfig struct {
Timeout time.Duration Timeout time.Duration
DodosCount uint DodosCount uint
RequestCount uint RequestCount uint
Duration time.Duration
Yes bool Yes bool
Params types.Params Params types.Params
Headers types.Headers Headers types.Headers
@ -47,6 +49,7 @@ func NewRequestConfig(conf *Config) *RequestConfig {
Timeout: conf.Timeout.Duration, Timeout: conf.Timeout.Duration,
DodosCount: *conf.DodosCount, DodosCount: *conf.DodosCount,
RequestCount: *conf.RequestCount, RequestCount: *conf.RequestCount,
Duration: conf.Duration.Duration,
Yes: *conf.Yes, Yes: *conf.Yes,
Params: conf.Params, Params: conf.Params,
Headers: conf.Headers, Headers: conf.Headers,
@ -57,6 +60,9 @@ func NewRequestConfig(conf *Config) *RequestConfig {
} }
func (rc *RequestConfig) GetValidDodosCountForRequests() uint { func (rc *RequestConfig) GetValidDodosCountForRequests() uint {
if rc.RequestCount == 0 {
return rc.DodosCount
}
return min(rc.DodosCount, rc.RequestCount) return min(rc.DodosCount, rc.RequestCount)
} }
@ -95,7 +101,17 @@ func (rc *RequestConfig) Print() {
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Dodos", rc.DodosCount}) t.AppendRow(table.Row{"Dodos", rc.DodosCount})
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Requests", rc.RequestCount}) if rc.RequestCount > 0 {
t.AppendRow(table.Row{"Requests", rc.RequestCount})
} else {
t.AppendRow(table.Row{"Requests"})
}
t.AppendSeparator()
if rc.Duration > 0 {
t.AppendRow(table.Row{"Duration", rc.Duration})
} else {
t.AppendRow(table.Row{"Duration"})
}
t.AppendSeparator() t.AppendSeparator()
t.AppendRow(table.Row{"Params", rc.Params.String()}) t.AppendRow(table.Row{"Params", rc.Params.String()})
t.AppendSeparator() t.AppendSeparator()
@ -116,6 +132,7 @@ type Config struct {
Timeout *types.Timeout `json:"timeout" yaml:"timeout"` Timeout *types.Timeout `json:"timeout" yaml:"timeout"`
DodosCount *uint `json:"dodos" yaml:"dodos"` DodosCount *uint `json:"dodos" yaml:"dodos"`
RequestCount *uint `json:"requests" yaml:"requests"` RequestCount *uint `json:"requests" yaml:"requests"`
Duration *types.Duration `json:"duration" yaml:"duration"`
Yes *bool `json:"yes" yaml:"yes"` Yes *bool `json:"yes" yaml:"yes"`
Params types.Params `json:"params" yaml:"params"` Params types.Params `json:"params" yaml:"params"`
Headers types.Headers `json:"headers" yaml:"headers"` Headers types.Headers `json:"headers" yaml:"headers"`
@ -162,8 +179,8 @@ func (c *Config) Validate() []error {
if utils.IsNilOrZero(c.DodosCount) { if utils.IsNilOrZero(c.DodosCount) {
errs = append(errs, errors.New("dodos count must be greater than 0")) errs = append(errs, errors.New("dodos count must be greater than 0"))
} }
if utils.IsNilOrZero(c.RequestCount) { if utils.IsNilOrZero(c.Duration) && utils.IsNilOrZero(c.RequestCount) {
errs = append(errs, errors.New("request count must be greater than 0")) errs = append(errs, errors.New("you should provide at least one of duration or request count"))
} }
for i, proxy := range c.Proxies { for i, proxy := range c.Proxies {
@ -197,6 +214,9 @@ func (config *Config) MergeConfig(newConfig *Config) {
if newConfig.RequestCount != nil { if newConfig.RequestCount != nil {
config.RequestCount = newConfig.RequestCount config.RequestCount = newConfig.RequestCount
} }
if newConfig.Duration != nil {
config.Duration = newConfig.Duration
}
if newConfig.Yes != nil { if newConfig.Yes != nil {
config.Yes = newConfig.Yes config.Yes = newConfig.Yes
} }
@ -230,6 +250,9 @@ func (config *Config) SetDefaults() {
if config.RequestCount == nil { if config.RequestCount == nil {
config.RequestCount = utils.ToPtr(DefaultRequestCount) config.RequestCount = utils.ToPtr(DefaultRequestCount)
} }
if config.Duration == nil {
config.Duration = &types.Duration{Duration: DefaultDuration}
}
if config.Yes == nil { if config.Yes == nil {
config.Yes = utils.ToPtr(DefaultYes) config.Yes = utils.ToPtr(DefaultYes)
} }

View File

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

View File

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

View File

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

View File

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

57
types/timeout.go Normal file
View File

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