1package google
2
3import (
4 "context"
5 "net/http"
6
7 "charm.land/fantasy"
8 "charm.land/fantasy/providers/internal/httpheaders"
9)
10
11type callUAKey struct{}
12
13func withCallUA(ctx context.Context, call fantasy.Call) context.Context {
14 if ua, ok := httpheaders.CallUserAgent(call.UserAgent); ok {
15 return context.WithValue(ctx, callUAKey{}, ua)
16 }
17 return ctx
18}
19
20func withObjectCallUA(ctx context.Context, call fantasy.ObjectCall) context.Context {
21 if ua, ok := httpheaders.CallUserAgent(call.UserAgent); ok {
22 return context.WithValue(ctx, callUAKey{}, ua)
23 }
24 return ctx
25}
26
27func wrapHTTPClient(c *http.Client) *http.Client {
28 if c == nil {
29 c = http.DefaultClient
30 }
31 transport := c.Transport
32 if transport == nil {
33 transport = http.DefaultTransport
34 }
35 return &http.Client{
36 Transport: &uaTransport{base: transport},
37 CheckRedirect: c.CheckRedirect,
38 Jar: c.Jar,
39 Timeout: c.Timeout,
40 }
41}
42
43type uaTransport struct {
44 base http.RoundTripper
45}
46
47func (t *uaTransport) RoundTrip(req *http.Request) (*http.Response, error) {
48 if ua, ok := req.Context().Value(callUAKey{}).(string); ok && ua != "" {
49 req = req.Clone(req.Context())
50 req.Header.Set("User-Agent", ua)
51 }
52 return t.base.RoundTrip(req)
53}