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 +}