tailscale/prober/http.go
Will Norris 71029cea2d all: update copyright and license headers
This updates all source files to use a new standard header for copyright
and license declaration.  Notably, copyright no longer includes a date,
and we now use the standard SPDX-License-Identifier header.

This commit was done almost entirely mechanically with perl, and then
some minimal manual fixes.

Updates #6865

Signed-off-by: Will Norris <will@tailscale.com>
2023-01-27 15:36:29 -08:00

61 lines
1.4 KiB
Go

// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package prober
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
)
const maxHTTPBody = 4 << 20 // MiB
// HTTP returns a Probe that healthchecks an HTTP URL.
//
// The ProbeFunc sends a GET request for url, expects an HTTP 200
// response, and verifies that want is present in the response
// body.
func HTTP(url, wantText string) ProbeFunc {
return func(ctx context.Context) error {
return probeHTTP(ctx, url, []byte(wantText))
}
}
func probeHTTP(ctx context.Context, url string, want []byte) error {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return fmt.Errorf("constructing request: %w", err)
}
// Get a completely new transport each time, so we don't reuse a
// past connection.
tr := http.DefaultTransport.(*http.Transport).Clone()
defer tr.CloseIdleConnections()
c := &http.Client{
Transport: tr,
}
resp, err := c.Do(req)
if err != nil {
return fmt.Errorf("fetching %q: %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("fetching %q: status code %d, want 200", url, resp.StatusCode)
}
bs, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPBody))
if err != nil {
return fmt.Errorf("reading body of %q: %w", url, err)
}
if !bytes.Contains(bs, want) {
return fmt.Errorf("body of %q does not contain %q", url, want)
}
return nil
}