Skip to content

Commit

Permalink
Fix versioning for planetscale-go headers (#218)
Browse files Browse the repository at this point in the history
* Fix user agents for planetscale-go

* Get version from dependency path, rather than from main module
  • Loading branch information
iheanyi authored Oct 11, 2024
1 parent 264d853 commit 4851f5b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
23 changes: 17 additions & 6 deletions planetscale/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/url"
"runtime/debug"
"strconv"

"github.com/hashicorp/go-cleanhttp"
Expand All @@ -20,11 +21,6 @@ const (
jsonMediaType = "application/json"
)

const (
libraryVersion = "v0.67.0"
userAgent = "planetscale-go/" + libraryVersion
)

// ErrorCode defines the code of an error.
type ErrorCode string

Expand Down Expand Up @@ -133,6 +129,21 @@ func WithPerPage(perPage int) ListOption {
// ClientOption provides a variadic option for configuring the client
type ClientOption func(c *Client) error

func defaultUserAgent() string {
libraryVersion := "unknown"
buildInfo, ok := debug.ReadBuildInfo()
if ok {
for _, dep := range buildInfo.Deps {
if dep.Path == "github.com/planetscale/planetscale-go" {
libraryVersion = dep.Version
break
}
}
}

return "planetscale-go/" + libraryVersion
}

// WithUserAgent overrides the User-Agent header.
func WithUserAgent(userAgent string) ClientOption {
return func(c *Client) error {
Expand Down Expand Up @@ -223,7 +234,7 @@ func NewClient(opts ...ClientOption) (*Client, error) {
c := &Client{
client: cleanhttp.DefaultClient(),
baseURL: baseURL,
UserAgent: userAgent,
UserAgent: defaultUserAgent(),
headers: make(map[string]string, 0),
}

Expand Down
4 changes: 2 additions & 2 deletions planetscale/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func TestDo(t *testing.T) {
response: `{}`,
method: http.MethodGet,
wantHeaders: map[string]string{
"User-Agent": "planetscale-go/v0.67.0",
"User-Agent": "planetscale-go/unknown",
},
},
{
Expand All @@ -39,7 +39,7 @@ func TestDo(t *testing.T) {
clientOptions: []ClientOption{WithUserAgent("test-user-agent"), WithRequestHeaders(map[string]string{"Test-Header": "test-value"})},
wantHeaders: map[string]string{
"Test-Header": "test-value",
"User-Agent": "test-user-agent planetscale-go/v0.67.0",
"User-Agent": "test-user-agent planetscale-go/unknown",
},
},
{
Expand Down

0 comments on commit 4851f5b

Please sign in to comment.