Skip to content

Commit 4851f5b

Browse files
authored
Fix versioning for planetscale-go headers (#218)
* Fix user agents for planetscale-go * Get version from dependency path, rather than from main module
1 parent 264d853 commit 4851f5b

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

planetscale/client.go

+17-6
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"io"
99
"net/http"
1010
"net/url"
11+
"runtime/debug"
1112
"strconv"
1213

1314
"github.com/hashicorp/go-cleanhttp"
@@ -20,11 +21,6 @@ const (
2021
jsonMediaType = "application/json"
2122
)
2223

23-
const (
24-
libraryVersion = "v0.67.0"
25-
userAgent = "planetscale-go/" + libraryVersion
26-
)
27-
2824
// ErrorCode defines the code of an error.
2925
type ErrorCode string
3026

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

132+
func defaultUserAgent() string {
133+
libraryVersion := "unknown"
134+
buildInfo, ok := debug.ReadBuildInfo()
135+
if ok {
136+
for _, dep := range buildInfo.Deps {
137+
if dep.Path == "github.com/planetscale/planetscale-go" {
138+
libraryVersion = dep.Version
139+
break
140+
}
141+
}
142+
}
143+
144+
return "planetscale-go/" + libraryVersion
145+
}
146+
136147
// WithUserAgent overrides the User-Agent header.
137148
func WithUserAgent(userAgent string) ClientOption {
138149
return func(c *Client) error {
@@ -223,7 +234,7 @@ func NewClient(opts ...ClientOption) (*Client, error) {
223234
c := &Client{
224235
client: cleanhttp.DefaultClient(),
225236
baseURL: baseURL,
226-
UserAgent: userAgent,
237+
UserAgent: defaultUserAgent(),
227238
headers: make(map[string]string, 0),
228239
}
229240

planetscale/client_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func TestDo(t *testing.T) {
2828
response: `{}`,
2929
method: http.MethodGet,
3030
wantHeaders: map[string]string{
31-
"User-Agent": "planetscale-go/v0.67.0",
31+
"User-Agent": "planetscale-go/unknown",
3232
},
3333
},
3434
{
@@ -39,7 +39,7 @@ func TestDo(t *testing.T) {
3939
clientOptions: []ClientOption{WithUserAgent("test-user-agent"), WithRequestHeaders(map[string]string{"Test-Header": "test-value"})},
4040
wantHeaders: map[string]string{
4141
"Test-Header": "test-value",
42-
"User-Agent": "test-user-agent planetscale-go/v0.67.0",
42+
"User-Agent": "test-user-agent planetscale-go/unknown",
4343
},
4444
},
4545
{

0 commit comments

Comments
 (0)