|
14 | 14 |
|
15 | 15 | package transport |
16 | 16 |
|
17 | | -import "net/http" |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "net/http" |
| 20 | + "runtime/debug" |
| 21 | +) |
18 | 22 |
|
19 | 23 | const ( |
20 | | - transportName = "go-containerregistry" |
| 24 | + defaultUserAgent = "go-containerregistry" |
| 25 | + moduleName = "github.com/google/go-containerregistry" |
21 | 26 | ) |
22 | 27 |
|
23 | | -type useragentTransport struct { |
24 | | - // Wrapped by useragentTransport. |
| 28 | +var ggcrVersion = defaultUserAgent |
| 29 | + |
| 30 | +type userAgentTransport struct { |
25 | 31 | inner http.RoundTripper |
| 32 | + ua string |
| 33 | +} |
| 34 | + |
| 35 | +func init() { |
| 36 | + if v := version(); v != "" { |
| 37 | + ggcrVersion = fmt.Sprintf("%s/%s", defaultUserAgent, v) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +func version() string { |
| 42 | + info, ok := debug.ReadBuildInfo() |
| 43 | + if !ok { |
| 44 | + return "" |
| 45 | + } |
| 46 | + |
| 47 | + // Happens for crane and gcrane. |
| 48 | + if info.Main.Path == moduleName { |
| 49 | + return info.Main.Version |
| 50 | + } |
| 51 | + |
| 52 | + // Anything else. |
| 53 | + for _, dep := range info.Deps { |
| 54 | + if dep.Path == moduleName { |
| 55 | + return dep.Version |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return "" |
| 60 | +} |
| 61 | + |
| 62 | +// NewUserAgent returns an http.Roundtripper that sets the user agent to |
| 63 | +// The provided string plus additional go-containerregistry information, |
| 64 | +// e.g. if provided "crane/v0.1.4" and this modules was built at v0.1.4: |
| 65 | +// |
| 66 | +// User-Agent: crane/v0.1.4 go-containerregistry/v0.1.4 |
| 67 | +func NewUserAgent(inner http.RoundTripper, ua string) http.RoundTripper { |
| 68 | + if ua == "" { |
| 69 | + ua = ggcrVersion |
| 70 | + } else { |
| 71 | + ua = fmt.Sprintf("%s %s", ua, ggcrVersion) |
| 72 | + } |
| 73 | + return &userAgentTransport{ |
| 74 | + inner: inner, |
| 75 | + ua: ua, |
| 76 | + } |
26 | 77 | } |
27 | 78 |
|
28 | 79 | // RoundTrip implements http.RoundTripper |
29 | | -func (ut *useragentTransport) RoundTrip(in *http.Request) (*http.Response, error) { |
30 | | - in.Header.Set("User-Agent", transportName) |
| 80 | +func (ut *userAgentTransport) RoundTrip(in *http.Request) (*http.Response, error) { |
| 81 | + in.Header.Set("User-Agent", ut.ua) |
31 | 82 | return ut.inner.RoundTrip(in) |
32 | 83 | } |
0 commit comments