push.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package internal // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/lokireceiver/internal"
  4. import (
  5. "compress/flate"
  6. "compress/gzip"
  7. "fmt"
  8. "io"
  9. "math"
  10. "mime"
  11. "net/http"
  12. "github.com/grafana/loki/pkg/push"
  13. )
  14. var (
  15. contentType = http.CanonicalHeaderKey("Content-Type")
  16. contentEnc = http.CanonicalHeaderKey("Content-Encoding")
  17. )
  18. const applicationJSON = "application/json"
  19. func ParseRequest(req *http.Request) (*push.PushRequest, error) {
  20. var body io.Reader
  21. contentEncoding := req.Header.Get(contentEnc)
  22. switch contentEncoding {
  23. case "", "snappy":
  24. body = req.Body
  25. case "gzip":
  26. gzipReader, err := gzip.NewReader(req.Body)
  27. if err != nil {
  28. return nil, err
  29. }
  30. defer gzipReader.Close()
  31. body = gzipReader
  32. case "deflate":
  33. flateReader := flate.NewReader(req.Body)
  34. defer flateReader.Close()
  35. body = flateReader
  36. default:
  37. return nil, fmt.Errorf("Content-Encoding %q not supported", contentEncoding)
  38. }
  39. var pushRequest push.PushRequest
  40. reqContentType := req.Header.Get(contentType)
  41. reqContentType, _ /* params */, err := mime.ParseMediaType(reqContentType)
  42. if err != nil {
  43. return nil, err
  44. }
  45. switch reqContentType {
  46. case applicationJSON:
  47. if err = decodePushRequest(body, &pushRequest); err != nil {
  48. return nil, err
  49. }
  50. default:
  51. // When no content-type header is set or when it is set to
  52. // `application/x-protobuf`: expect snappy compression.
  53. if err := parseProtoReader(body, int(req.ContentLength), math.MaxInt32, &pushRequest); err != nil {
  54. return nil, err
  55. }
  56. return &pushRequest, nil
  57. }
  58. return &pushRequest, nil
  59. }