Skip to content

Commit 17a6922

Browse files
committed
refactor: replace readResponseBody with io.LimitReader for response handling
1 parent f9b6008 commit 17a6922

File tree

1 file changed

+2
-37
lines changed

1 file changed

+2
-37
lines changed

plugins/outputs/opentelemetry/client_http.go

Lines changed: 2 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"bytes"
55
"context"
66
"crypto/tls"
7-
"errors"
87
"fmt"
98
"io"
109
"net/http"
@@ -100,7 +99,8 @@ func (h *httpClient) Export(ctx context.Context, request pmetricotlp.ExportReque
10099
http.StatusText(httpResponse.StatusCode), httpResponse.StatusCode)
101100
}
102101

103-
responseBytes, err := readResponseBody(httpResponse)
102+
r := io.LimitReader(httpResponse.Body, 64*1024)
103+
responseBytes, err := io.ReadAll(r)
104104
if err != nil {
105105
return pmetricotlp.ExportResponse{}, err
106106
}
@@ -126,38 +126,3 @@ func (h *httpClient) Close() error {
126126
h.httpClient.CloseIdleConnections()
127127
return nil
128128
}
129-
130-
// ref. https://github.com/open-telemetry/opentelemetry-collector/blob/7258150320ae4c3b489aa58bd2939ba358b23ae1/exporter/otlphttpexporter/otlp.go#L271
131-
func readResponseBody(resp *http.Response) ([]byte, error) {
132-
if resp.ContentLength == 0 {
133-
return nil, nil
134-
}
135-
136-
maxRead := resp.ContentLength
137-
138-
// if maxRead == -1, the ContentLength header has not been sent, so read up to
139-
// the maximum permitted body size. If it is larger than the permitted body
140-
// size, still try to read from the body in case the value is an error. If the
141-
// body is larger than the maximum size, proto unmarshaling will likely fail.
142-
// 64KB is a not specific limit. But, opentelemetry-collector also uses 64KB for safety.
143-
if maxRead == -1 || maxRead > 64*1024 {
144-
maxRead = 64 * 1024
145-
}
146-
protoBytes := make([]byte, maxRead)
147-
n, err := io.ReadFull(resp.Body, protoBytes)
148-
149-
// No bytes read and an EOF error indicates there is no body to read.
150-
if n == 0 && (err == nil || errors.Is(err, io.EOF)) {
151-
return nil, nil
152-
}
153-
154-
// io.ReadFull will return io.ErrorUnexpectedEOF if the Content-Length header
155-
// wasn't set, since we will try to read past the length of the body. If this
156-
// is the case, the body will still have the full message in it, so we want to
157-
// ignore the error and parse the message.
158-
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
159-
return nil, err
160-
}
161-
162-
return protoBytes[:n], nil
163-
}

0 commit comments

Comments
 (0)