Other: Make user-agent implementation threadsafe

This commit is contained in:
James Houlahan
2022-10-24 16:12:37 +02:00
parent 798cd5caf3
commit d0fb3509cc

View File

@ -21,10 +21,13 @@ import (
"fmt" "fmt"
"regexp" "regexp"
"runtime" "runtime"
"sync"
) )
type UserAgent struct { type UserAgent struct {
client, platform string client, platform string
lock sync.RWMutex
} }
func New() *UserAgent { func New() *UserAgent {
@ -35,18 +38,30 @@ func New() *UserAgent {
} }
func (ua *UserAgent) SetClient(name, version string) { func (ua *UserAgent) SetClient(name, version string) {
ua.lock.Lock()
defer ua.lock.Unlock()
ua.client = fmt.Sprintf("%v/%v", name, regexp.MustCompile(`(.*) \((.*)\)`).ReplaceAllString(version, "$1-$2")) ua.client = fmt.Sprintf("%v/%v", name, regexp.MustCompile(`(.*) \((.*)\)`).ReplaceAllString(version, "$1-$2"))
} }
func (ua *UserAgent) HasClient() bool { func (ua *UserAgent) HasClient() bool {
ua.lock.RLock()
defer ua.lock.RUnlock()
return ua.client != "" return ua.client != ""
} }
func (ua *UserAgent) SetPlatform(platform string) { func (ua *UserAgent) SetPlatform(platform string) {
ua.lock.Lock()
defer ua.lock.Unlock()
ua.platform = platform ua.platform = platform
} }
func (ua *UserAgent) GetUserAgent() string { func (ua *UserAgent) GetUserAgent() string {
ua.lock.RLock()
defer ua.lock.RUnlock()
var client string var client string
if ua.client != "" { if ua.client != "" {