From b52892fb6733066d2ad4e3bbec0204f4f3d99834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patryk=20Ma=C5=82ek?= Date: Tue, 5 Nov 2024 17:54:40 +0100 Subject: [PATCH] chore: fix setting user agent --- internal/hooks/registration.go | 34 ---------------------------------- internal/hooks/user_agent.go | 21 +++++++++++++++++++++ pkg/metadata/metadata.go | 24 ++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 34 deletions(-) delete mode 100644 internal/hooks/registration.go create mode 100644 internal/hooks/user_agent.go create mode 100644 pkg/metadata/metadata.go diff --git a/internal/hooks/registration.go b/internal/hooks/registration.go deleted file mode 100644 index ba97733..0000000 --- a/internal/hooks/registration.go +++ /dev/null @@ -1,34 +0,0 @@ -package hooks - -import ( - "net/http" - "sync" -) - -var ( - l sync.RWMutex - userAgent string - defaultUserAgent = "SpeakeasyGoSDK/0.1" -) - -func SetUserAgent(ua string) { - l.Lock() - defer l.Unlock() - userAgent = ua -} - -func GetUserAgent() string { - l.RLock() - defer l.RUnlock() - return userAgent -} - -type UserAgentPreRequestHook struct{} - -var _ beforeRequestHook = (*UserAgentPreRequestHook)(nil) - -func (i *UserAgentPreRequestHook) BeforeRequest(hookCtx BeforeRequestContext, req *http.Request) (*http.Request, error) { - req.Header.Set("User-Agent", GetUserAgent()) - - return req, nil -} diff --git a/internal/hooks/user_agent.go b/internal/hooks/user_agent.go new file mode 100644 index 0000000..3658326 --- /dev/null +++ b/internal/hooks/user_agent.go @@ -0,0 +1,21 @@ +package hooks + +import ( + "net/http" + + "github.com/Kong/sdk-konnect-go/pkg/metadata" +) + +type UserAgentPreRequestHook struct{} + +var _ beforeRequestHook = (*UserAgentPreRequestHook)(nil) + +func (i *UserAgentPreRequestHook) BeforeRequest(hookCtx BeforeRequestContext, req *http.Request) (*http.Request, error) { + ua := metadata.GetUserAgent() + if ua != "" { + req.Header.Set("User-Agent", ua) + return req, nil + } + + return req, nil +} diff --git a/pkg/metadata/metadata.go b/pkg/metadata/metadata.go new file mode 100644 index 0000000..1077388 --- /dev/null +++ b/pkg/metadata/metadata.go @@ -0,0 +1,24 @@ +package metadata + +import "sync" + +var ( + l sync.RWMutex + userAgent string +) + +// SetUserAgent sets the user agent to be used by the SDK. +// This is then used by UserAgentPreRequestHook in internal/hooks/user_agent.go +func SetUserAgent(ua string) { + l.Lock() + defer l.Unlock() + userAgent = ua +} + +// GetUserAgent returns the user agent to be used by the SDK. +// This is then used by UserAgentPreRequestHook in internal/hooks/user_agent.go +func GetUserAgent() string { + l.RLock() + defer l.RUnlock() + return userAgent +}