| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package httpsd |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/netdata/netdata/go/plugins/pkg/confopt" |
| 13 | "github.com/netdata/netdata/go/plugins/pkg/web" |
| 14 | ) |
| 15 | |
| 16 | const ( |
| 17 | defaultInterval = time.Minute |
| 18 | defaultTimeout = 2 * time.Second |
| 19 | |
| 20 | responseBodyLimit = 10 * 1024 * 1024 |
| 21 | |
| 22 | formatAuto = "auto" |
| 23 | formatJSON = "json" |
| 24 | formatYAML = "yaml" |
| 25 | ) |
| 26 | |
| 27 | type Config struct { |
| 28 | Source string `yaml:"-" json:"-"` |
| 29 | |
| 30 | web.HTTPConfig `yaml:",inline" json:""` |
| 31 | |
| 32 | Interval *confopt.LongDuration `yaml:"interval,omitempty" json:"interval,omitempty"` |
| 33 | Format string `yaml:"format,omitempty" json:"format,omitempty"` |
| 34 | } |
| 35 | |
| 36 | func (c Config) validate() error { |
| 37 | if strings.TrimSpace(c.URL) == "" { |
| 38 | return errors.New("url is required") |
| 39 | } |
| 40 | |
| 41 | u, err := url.Parse(c.URL) |
| 42 | if err != nil { |
| 43 | return fmt.Errorf("invalid url: %w", err) |
| 44 | } |
| 45 | switch u.Scheme { |
| 46 | case "http", "https": |
| 47 | default: |
| 48 | return fmt.Errorf("unsupported url scheme %q", u.Scheme) |
| 49 | } |
| 50 | if u.Host == "" { |
| 51 | return errors.New("url host is required") |
| 52 | } |
| 53 | |
| 54 | switch c.format() { |
| 55 | case formatAuto, formatJSON, formatYAML: |
| 56 | default: |
| 57 | return fmt.Errorf("unsupported format %q", c.Format) |
| 58 | } |
| 59 | |
| 60 | if c.Interval != nil && c.Interval.Duration() < 0 { |
| 61 | return errors.New("interval cannot be negative") |
| 62 | } |
| 63 | |
| 64 | return nil |
| 65 | } |
| 66 | |
| 67 | func (c Config) interval() time.Duration { |
| 68 | if c.Interval == nil { |
| 69 | return defaultInterval |
| 70 | } |
| 71 | return c.Interval.Duration() |
| 72 | } |
| 73 | |
| 74 | func (c Config) clientConfig() web.ClientConfig { |
| 75 | cfg := c.ClientConfig |
| 76 | if cfg.Timeout.Duration() <= 0 { |
| 77 | cfg.Timeout = confopt.Duration(defaultTimeout) |
| 78 | } |
| 79 | return cfg |
| 80 | } |
| 81 | |
| 82 | func (c Config) format() string { |
| 83 | if v := strings.TrimSpace(strings.ToLower(c.Format)); v != "" { |
| 84 | return v |
| 85 | } |
| 86 | return formatAuto |
| 87 | } |