-1

In golang, it seems no hook methods exist for http.client, so I'm wondering how can I add extra headers like trace-id: xxx in framework.

Ideal code is like below:

// this func add a hook method to http-client to rewrite header
client := buildWithRewriteHeaderHook()
//customRequest has no `trace-id`
client.Do(customRequest)
// remote server get trace-id from http headers
...

PS: I know how to add headers to a request by 'req.setHeader()', and in my opinion it's not a duplicate question to this one. How to set headers in http get request?

AndyChow
  • 103
  • 10
  • The "hook" is the Transport field. You can easily write your own RoundTripper that wraps http.DefaultTransport, for instance. – Peter Mar 27 '19 at 08:48
  • @Abdullah No, it's not. I cannot hack building custom request, cos it's out of my control. It might be an option to hack http.client. – AndyChow Mar 27 '19 at 09:17
  • @Peter According to the official doc, it's not safe. https://golang.org/pkg/net/http/#RoundTripper . quote: RoundTrip should not modify the request, except for consuming and closing the Request's Body. RoundTrip may read fields of the request in a separate goroutine. – AndyChow Mar 27 '19 at 09:42
  • 1
    Good point, I forgot about that. At my workplace we wrap the whole client, actually. The Do method is all you need to send requets, so you can declare your own one-method interface which lends itself nicely to composition. You can take a look at [our package](https://godoc.org/github.com/classmarkets/cmhttp#WithHeader) for inspiration. – Peter Mar 27 '19 at 10:25
  • Thanks a lot. Maybe I should forget about the manual as long as it works in my scene. – AndyChow Apr 08 '19 at 09:00

1 Answers1

0

You should use headers.

You can do:

r.Header.Add("trace-id", "yourid")

You can also use open source package such as the opentracing one, which follows open tracing conventions and has method to add and read tracing information from requests: https://github.com/opentracing/opentracing-go

Francois
  • 3,050
  • 13
  • 21