http.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package prober
  4. import (
  5. "bytes"
  6. "context"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. )
  11. const maxHTTPBody = 4 << 20 // MiB
  12. // HTTP returns a ProbeClass that healthchecks an HTTP URL.
  13. //
  14. // The probe function sends a GET request for url, expects an HTTP 200
  15. // response, and verifies that want is present in the response
  16. // body.
  17. func HTTP(url, wantText string) ProbeClass {
  18. return ProbeClass{
  19. Probe: func(ctx context.Context) error {
  20. return probeHTTP(ctx, url, []byte(wantText))
  21. },
  22. Class: "http",
  23. }
  24. }
  25. func probeHTTP(ctx context.Context, url string, want []byte) error {
  26. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  27. if err != nil {
  28. return fmt.Errorf("constructing request: %w", err)
  29. }
  30. // Get a completely new transport each time, so we don't reuse a
  31. // past connection.
  32. tr := http.DefaultTransport.(*http.Transport).Clone()
  33. defer tr.CloseIdleConnections()
  34. c := &http.Client{
  35. Transport: tr,
  36. }
  37. resp, err := c.Do(req)
  38. if err != nil {
  39. return fmt.Errorf("fetching %q: %w", url, err)
  40. }
  41. defer resp.Body.Close()
  42. if resp.StatusCode != 200 {
  43. return fmt.Errorf("fetching %q: status code %d, want 200", url, resp.StatusCode)
  44. }
  45. bs, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPBody))
  46. if err != nil {
  47. return fmt.Errorf("reading body of %q: %w", url, err)
  48. }
  49. if !bytes.Contains(bs, want) {
  50. // Log response body, but truncate it if it's too large; the limit
  51. // has been chosen arbitrarily.
  52. if maxlen := 300; len(bs) > maxlen {
  53. bs = bs[:maxlen]
  54. }
  55. return fmt.Errorf("body of %q does not contain %q (got: %q)", url, want, string(bs))
  56. }
  57. return nil
  58. }