Skip to content

Commit

Permalink
fix: Parse number Durations in config correctly (fix #221)
Browse files Browse the repository at this point in the history
This error edge case was introduced by #218.
  • Loading branch information
robinbraemer committed Jul 20, 2023
1 parent 3f7b4c4 commit 59afe39
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pkg/edition/java/lite/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type (
Route struct {
Host configutil.SingleOrMulti[string] `json:"host" yaml:"host"`
Backend configutil.SingleOrMulti[string] `json:"backend" yaml:"backend"`
CachePingTTL time.Duration `json:"cachePingTTL,omitempty" yaml:"cachePingTTL,omitempty"` // 0 = default, < 0 = disabled
CachePingTTL configutil.Duration `json:"cachePingTTL,omitempty" yaml:"cachePingTTL,omitempty"` // 0 = default, < 0 = disabled
Fallback *Status `json:"fallback,omitempty" yaml:"fallback,omitempty"` // nil = disabled
ProxyProtocol bool `json:"proxyProtocol,omitempty" yaml:"proxyProtocol,omitempty"`
RealIP bool `json:"realIP,omitempty" yaml:"realIP,omitempty"`
Expand Down Expand Up @@ -73,7 +73,7 @@ func (r *Route) GetCachePingTTL() time.Duration {
if r.CachePingTTL == 0 {
return defaultTTL
}
return r.CachePingTTL
return time.Duration(r.CachePingTTL)
}

// CachePingEnabled returns true if the route has a ping cache enabled.
Expand Down
40 changes: 40 additions & 0 deletions pkg/util/configutil/duration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package configutil

import (
"encoding/json"
"fmt"
"time"
)

// Duration is a configuration duration.
// It is a wrapper around time.Duration that implements the json.Marshaler and json.Unmarshaler interfaces.
//
// - string is parsed using time.ParseDuration.
// - int64 and float64 are interpreted as seconds.
type Duration time.Duration

func (d *Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(*d).String())
}

func (d *Duration) UnmarshalJSON(data []byte) error {
var a any
if err := json.Unmarshal(data, &a); err != nil {
return err
}
switch v := a.(type) {
case string:
dur, err := time.ParseDuration(v)
if err != nil {
return err
}
*d = Duration(dur)
case float64:
*d = Duration(time.Duration(v) * time.Second)
case int64:
*d = Duration(time.Duration(v) * time.Second)
default:
return fmt.Errorf("invalid duration type %T: %v", v, v)
}
return nil
}

0 comments on commit 59afe39

Please sign in to comment.