Debian Codegraph @

instrumentation/net/http/otelhttp/internal/request/body_wrapper.go

raw
1 // Code generated by gotmpl. DO NOT MODIFY.
2 // source: internal/shared/request/body_wrapper.go.tmpl
3
4 // Copyright The OpenTelemetry Authors
5 // SPDX-License-Identifier: Apache-2.0
6
7 // Package request provides types and functionality to handle HTTP request
8 // handling.
9 package request // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request"
10
11 import (
12 "io"
13 "sync"
14 )
15
16 var _ io.ReadCloser = &BodyWrapper{}
17
18 // BodyWrapper wraps a http.Request.Body (an io.ReadCloser) to track the number
19 // of bytes read and the last error.
20 type BodyWrapper struct {
21 io.ReadCloser
22 OnRead func(n int64) // must not be nil
23
24 mu sync.Mutex
25 read int64
26 err error
27 }
28
29 // NewBodyWrapper creates a new BodyWrapper.
30 //
31 // The onRead attribute is a callback that will be called every time the data
32 // is read, with the number of bytes being read.
33 func NewBodyWrapper(body io.ReadCloser, onRead func(int64)) *BodyWrapper {
34 return &BodyWrapper{
35 ReadCloser: body,
36 OnRead: onRead,
37 }
38 }
39
40 // Read reads the data from the io.ReadCloser, and stores the number of bytes
41 // read and the error.
42 func (w *BodyWrapper) Read(b []byte) (int, error) {
43 n, err := w.ReadCloser.Read(b)
44 n1 := int64(n)
45
46 w.updateReadData(n1, err)
47 w.OnRead(n1)
48 return n, err
49 }
50
51 func (w *BodyWrapper) updateReadData(n int64, err error) {
52 w.mu.Lock()
53 defer w.mu.Unlock()
54
55 w.read += n
56 if err != nil {
57 w.err = err
58 }
59 }
60
61 // Close closes the io.ReadCloser.
62 func (w *BodyWrapper) Close() error {
63 return w.ReadCloser.Close()
64 }
65
66 // BytesRead returns the number of bytes read up to this point.
67 func (w *BodyWrapper) BytesRead() int64 {
68 w.mu.Lock()
69 defer w.mu.Unlock()
70
71 return w.read
72 }
73
74 // Error returns the last error.
75 func (w *BodyWrapper) Error() error {
76 w.mu.Lock()
77 defer w.mu.Unlock()
78
79 return w.err
80 }