| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package confighttp |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"net" |
| 9 |
"net/http" |
| 10 |
|
| 11 |
"go.opentelemetry.io/collector/client" |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
type clientInfoHandler struct { |
| 16 |
next http.Handler |
| 17 |
|
| 18 |
|
| 19 |
includeMetadata bool |
| 20 |
} |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
func (h *clientInfoHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 25 |
req = req.WithContext(contextWithClient(req, h.includeMetadata)) |
| 26 |
h.next.ServeHTTP(w, req) |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
func contextWithClient(req *http.Request, includeMetadata bool) context.Context { |
| 32 |
cl := client.FromContext(req.Context()) |
| 33 |
|
| 34 |
ip := parseIP(req.RemoteAddr) |
| 35 |
if ip != nil { |
| 36 |
cl.Addr = ip |
| 37 |
} |
| 38 |
|
| 39 |
if includeMetadata { |
| 40 |
md := req.Header.Clone() |
| 41 |
if md.Get(client.MetadataHostName) == "" && req.Host != "" { |
| 42 |
md.Add(client.MetadataHostName, req.Host) |
| 43 |
} |
| 44 |
|
| 45 |
cl.Metadata = client.NewMetadata(md) |
| 46 |
} |
| 47 |
|
| 48 |
ctx := client.NewContext(req.Context(), cl) |
| 49 |
return ctx |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
func parseIP(source string) *net.IPAddr { |
| 55 |
ipstr, _, err := net.SplitHostPort(source) |
| 56 |
if err == nil { |
| 57 |
source = ipstr |
| 58 |
} |
| 59 |
ip := net.ParseIP(source) |
| 60 |
if ip != nil { |
| 61 |
return &net.IPAddr{ |
| 62 |
IP: ip, |
| 63 |
} |
| 64 |
} |
| 65 |
return nil |
| 66 |
} |