github.com/helmwave/helmwave@v0.36.4-0.20240509190856-b35563eba4c6/pkg/monitor/http/config.go (about)

     1  package http
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"crypto/tls"
     7  	"net/http"
     8  	"slices"
     9  
    10  	log "github.com/sirupsen/logrus"
    11  )
    12  
    13  const (
    14  	TYPE          = "http"
    15  	DefaultMethod = "HEAD"
    16  )
    17  
    18  // Config is the main monitor Config.
    19  type Config struct {
    20  	client        *http.Client      `yaml:"-" json:"-"`
    21  	log           *log.Entry        `yaml:"-" json:"-"`
    22  	URL           string            `yaml:"url" json:"url" jsonschema:"required,title=URL to query"`
    23  	Method        string            `yaml:"method" json:"method" jsonschema:"title=HTTP method,default=HEAD"`
    24  	Body          string            `yaml:"body" json:"body" jsonschema:"title=HTTP body,default="`
    25  	Headers       map[string]string `yaml:"headers" json:"headers" jsonschema:"title=HTTP headers to set"`
    26  	ExpectedCodes []int             `yaml:"expected_codes" json:"expected_codes" jsonschema:"required,title=Expected response codes"`
    27  	Insecure      bool              `yaml:"insecure" json:"insecure" jsonschema:"default=false"`
    28  }
    29  
    30  func NewConfig() *Config {
    31  	return &Config{
    32  		Method: DefaultMethod,
    33  	}
    34  }
    35  
    36  func (c *Config) Init(_ context.Context, logger *log.Entry) error {
    37  	c.client = &http.Client{
    38  		Transport: &http.Transport{
    39  			TLSClientConfig: &tls.Config{
    40  				InsecureSkipVerify: c.Insecure,
    41  			},
    42  		},
    43  		Timeout: 0,
    44  	}
    45  
    46  	c.log = logger
    47  
    48  	return nil
    49  }
    50  
    51  func (c *Config) Run(ctx context.Context) error {
    52  	body := bytes.NewBufferString(c.Body)
    53  
    54  	req, err := http.NewRequestWithContext(ctx, c.Method, c.URL, body)
    55  	if err != nil {
    56  		return NewRequestError(err)
    57  	}
    58  
    59  	for k, v := range c.Headers {
    60  		req.Header.Set(k, v)
    61  	}
    62  
    63  	resp, err := c.client.Do(req)
    64  	if err != nil {
    65  		return NewResponseError(err)
    66  	}
    67  	defer func() {
    68  		err := resp.Body.Close()
    69  		if err != nil {
    70  			c.log.WithError(err).Error("failed to close HTTP body")
    71  		}
    72  	}()
    73  
    74  	if !slices.Contains(c.ExpectedCodes, resp.StatusCode) {
    75  		return NewUnexpectedStatusError(resp.StatusCode)
    76  	}
    77  
    78  	return nil
    79  }
    80  
    81  func (c *Config) Validate() error {
    82  	if c.URL == "" {
    83  		return ErrURLEmpty
    84  	}
    85  
    86  	return nil
    87  }