Compare commits

..

No commits in common. "7e05cf4f6b5ced75a2ecbe733fd00c70c3568998" and "a170588574078f3df4f2dcbd49830bc3542d8be2" have entirely different histories.

10 changed files with 77 additions and 239 deletions

View File

@ -46,7 +46,6 @@ 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
``` ```
@ -57,21 +56,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), each with a timeout of 2 seconds, within a maximum duration of 1 minute: Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 2 seconds:
```sh ```sh
dodo -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 2s dodo -u https://example.com -m GET -d 10 -r 1000 -t 2s
``` ```
With Docker: With Docker:
```sh ```sh
docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 2s docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2s
``` ```
### 2. Config File Usage ### 2. Config File Usage
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: Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 800 milliseconds:
#### 2.1 JSON Example #### 2.1 JSON Example
@ -83,7 +82,6 @@ Send 1000 GET requests to https://example.com with 10 parallel dodos (threads),
"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
@ -161,7 +159,6 @@ 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
@ -233,29 +230,28 @@ 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 -o 1m -t 5s dodo -f /path/to/config.yaml -u https://example.com -m GET -d 10 -r 1000 -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 -o 1m -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 -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 | 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 | -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 | - |
| Timeout | timeout | -timeout | -t | Time | Timeout for canceling each request | 10s |
| Params | params | -param | -p | [{String: String OR [String]}] | Request parameters | - | | Params | params | -param | -p | [{String: String OR [String]}] | Request parameters | - |
| Headers | headers | -header | -H | [{String: String OR [String]}] | Request headers | - | | Headers | headers | -header | -H | [{String: String OR [String]}] | Request headers | - |
| Cookies | cookies | -cookie | -c | [{String: String OR [String]}] | Request cookies | - | | Cookies | cookies | -cookie | -c | [{String: String OR [String]}] | Request cookies | - |

View File

@ -5,7 +5,6 @@
"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,7 +4,6 @@ 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: Simple usage only with URL:
dodo -u https://example.com -o 1m dodo -u https://example.com
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 -o 3m -t 3s \ -d 10 -r 1000 -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,9 +39,8 @@ 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 -r, -requests uint Number of total requests (default %d)
-o, -duration Time Maximum duration for the test (e.g. 30s, 1m, 5h) -t, -timeout Duration Timeout for each request (e.g. 400ms, 15s, 1m10s) (default %v)
-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")
@ -56,6 +55,7 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
cliUsageText+"\n", cliUsageText+"\n",
DefaultYes, DefaultYes,
DefaultDodosCount, DefaultDodosCount,
DefaultRequestCount,
DefaultTimeout, DefaultTimeout,
DefaultMethod, DefaultMethod,
) )
@ -70,7 +70,6 @@ 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
) )
{ {
@ -95,9 +94,6 @@ 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)")
@ -143,8 +139,6 @@ 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,13 +15,12 @@ import (
) )
const ( const (
VERSION string = "0.6.2" VERSION string = "0.6.1"
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 = 0 DefaultRequestCount uint = 1
DefaultDuration time.Duration = 0
DefaultYes bool = false DefaultYes bool = false
) )
@ -33,7 +32,6 @@ 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
@ -49,7 +47,6 @@ 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,
@ -60,9 +57,6 @@ 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)
} }
@ -101,17 +95,7 @@ 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()
if rc.RequestCount > 0 {
t.AppendRow(table.Row{"Requests", rc.RequestCount}) 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()
@ -132,7 +116,6 @@ 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"`
@ -179,8 +162,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.Duration) && utils.IsNilOrZero(c.RequestCount) { if utils.IsNilOrZero(c.RequestCount) {
errs = append(errs, errors.New("you should provide at least one of duration or request count")) errs = append(errs, errors.New("request count must be greater than 0"))
} }
for i, proxy := range c.Proxies { for i, proxy := range c.Proxies {
@ -214,9 +197,6 @@ 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
} }
@ -250,9 +230,6 @@ 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,7 +7,6 @@ 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"
@ -50,10 +49,6 @@ 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 uint, total int64,
message string, message string,
increase <-chan int64, increase <-chan int64,
) { ) {
@ -27,26 +27,21 @@ 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: int64(total), Total: total,
} }
pw.AppendTracker(&dodosTracker) pw.AppendTracker(&dodosTracker)
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
if err := ctx.Err(); err == context.Canceled || err == context.DeadlineExceeded { if ctx.Err() != context.Canceled {
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,28 +59,17 @@ 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(int(dodosCount)) wg.Add(dodosCountInt)
streamWG.Add(1) streamWG.Add(1)
streamCtx, streamCtxCancel := context.WithCancel(context.Background()) streamCtx, streamCtxCancel := context.WithCancel(context.Background())
go streamProgress(streamCtx, &streamWG, requestConfig.RequestCount, "Dodos Working🔥", increase) go streamProgress(streamCtx, &streamWG, int64(requestConfig.RequestCount), "Dodos Working🔥", increase)
if requestConfig.RequestCount == 0 {
for i := range dodosCount {
go sendRequest(
ctx,
newRequest(*requestConfig, clients, int64(i)),
requestConfig.Timeout,
&responses[i],
increase,
&wg,
)
}
} else {
for i := range dodosCount { for i := range dodosCount {
if i+1 == dodosCount { if i+1 == dodosCount {
requestCountPerDodo = requestConfig.RequestCount - (i * requestConfig.RequestCount / dodosCount) requestCountPerDodo = requestConfig.RequestCount - (i * requestConfig.RequestCount / dodosCount)
@ -89,7 +78,7 @@ func releaseDodos(
(i * requestConfig.RequestCount / dodosCount) (i * requestConfig.RequestCount / dodosCount)
} }
go sendRequestByCount( go sendRequest(
ctx, ctx,
newRequest(*requestConfig, clients, int64(i)), newRequest(*requestConfig, clients, int64(i)),
requestConfig.Timeout, requestConfig.Timeout,
@ -99,19 +88,17 @@ func releaseDodos(
&wg, &wg,
) )
} }
}
wg.Wait() wg.Wait()
streamCtxCancel() streamCtxCancel()
streamWG.Wait() streamWG.Wait()
return utils.Flatten(responses) return utils.Flatten(responses)
} }
// sendRequestByCount sends a specified number of HTTP requests concurrently with a given timeout. // sendRequest 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 sendRequestByCount( func sendRequest(
ctx context.Context, ctx context.Context,
request *Request, request *Request,
timeout time.Duration, timeout time.Duration,
@ -155,50 +142,3 @@ func sendRequestByCount(
}() }()
} }
} }
// 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 Duration struct { type Timeout struct {
time.Duration time.Duration
} }
func (duration *Duration) UnmarshalJSON(b []byte) error { func (timeout *Timeout) 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:
duration.Duration = time.Duration(value) timeout.Duration = time.Duration(value)
return nil return nil
case string: case string:
var err error var err error
duration.Duration, err = time.ParseDuration(value) timeout.Duration, err = time.ParseDuration(value)
if err != nil { if err != nil {
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)") return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
} }
return nil return nil
default: default:
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)") return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
} }
} }
func (duration Duration) MarshalJSON() ([]byte, error) { func (timeout Timeout) MarshalJSON() ([]byte, error) {
return json.Marshal(duration.Duration.String()) return json.Marshal(timeout.Duration.String())
} }
func (duration *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error { func (timeout *Timeout) 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:
duration.Duration = time.Duration(value) timeout.Duration = time.Duration(value)
return nil return nil
case string: case string:
var err error var err error
duration.Duration, err = time.ParseDuration(value) timeout.Duration, err = time.ParseDuration(value)
if err != nil { if err != nil {
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)") return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
} }
return nil return nil
default: default:
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)") return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
} }
} }

View File

@ -1,57 +0,0 @@
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)")
}
}