From 9a1f2e6d7cd68d872bdac2cf27cbaad37c9fcd58 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 1 Jun 2023 13:50:30 +0200 Subject: [PATCH] dockerversion: remove insertUpstreamUserAgent() It was not really "inserting" anything, just formatting and appending. Simplify this by changing this in to a `getUpstreamUserAgent()` function which returns the upstream User-Agent (if any) into a `UpstreamClient()`. Signed-off-by: Sebastiaan van Stijn --- dockerversion/useragent.go | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/dockerversion/useragent.go b/dockerversion/useragent.go index bd65800e99..232a28acc9 100644 --- a/dockerversion/useragent.go +++ b/dockerversion/useragent.go @@ -18,11 +18,11 @@ type UAStringKey struct{} // // [docker client's UA] UpstreamClient([upstream client's UA]) func DockerUserAgent(ctx context.Context) string { - daemonUA := getDaemonUserAgent() - if upstreamUA := getUserAgentFromContext(ctx); len(upstreamUA) > 0 { - return insertUpstreamUserAgent(upstreamUA, daemonUA) + ua := getDaemonUserAgent() + if upstreamUA := getUpstreamUserAgent(ctx); upstreamUA != "" { + ua += " " + upstreamUA } - return daemonUA + return ua } var ( @@ -57,16 +57,23 @@ func getDaemonUserAgent() string { return daemonUA } -// getUserAgentFromContext returns the previously saved user-agent context stored in ctx, if one exists -func getUserAgentFromContext(ctx context.Context) string { +// getUpstreamUserAgent returns the previously saved user-agent context stored +// in ctx, if one exists, and formats it as: +// +// UpstreamClient() +// +// It returns an empty string if no user-agent is present in the context. +func getUpstreamUserAgent(ctx context.Context) string { var upstreamUA string if ctx != nil { - var ki interface{} = ctx.Value(UAStringKey{}) - if ki != nil { + if ki := ctx.Value(UAStringKey{}); ki != nil { upstreamUA = ctx.Value(UAStringKey{}).(string) } } - return upstreamUA + if upstreamUA == "" { + return "" + } + return fmt.Sprintf("UpstreamClient(%s)", escapeStr(upstreamUA)) } const charsToEscape = `();\` @@ -89,11 +96,3 @@ func escapeStr(s string) string { } return ret } - -// insertUpstreamUserAgent adds the upstream client useragent to create a user-agent -// string of the form: -// -// $dockerUA UpstreamClient($upstreamUA) -func insertUpstreamUserAgent(upstreamUA string, dockerUA string) string { - return fmt.Sprintf("%s UpstreamClient(%s)", dockerUA, escapeStr(upstreamUA)) -}