Skip to content

Commit 072dce4

Browse files
feat(client): add support for endpoint-specific base URLs in python
This also changes how `WithEnvironmentProduction()` and `WithBaseURL()` interact. Previously, `WithBaseURL()` would be overridden by `WithEnvironmentProduction()` if `WithEnvironmentProduction()` was later in the list of options; now, `WithBaseURL()` always takes precedence.
1 parent 3fabca6 commit 072dce4

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

internal/requestconfig/requestconfig.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,9 @@ type RequestConfig struct {
205205
Context context.Context
206206
Request *http.Request
207207
BaseURL *url.URL
208+
// DefaultBaseURL will be used if BaseURL is not explicitly overridden using
209+
// WithBaseURL.
210+
DefaultBaseURL *url.URL
208211
CustomHTTPDoer HTTPDoer
209212
HTTPClient *http.Client
210213
Middlewares []middleware
@@ -373,7 +376,11 @@ func retryDelay(res *http.Response, retryCount int) time.Duration {
373376

374377
func (cfg *RequestConfig) Execute() (err error) {
375378
if cfg.BaseURL == nil {
376-
return fmt.Errorf("requestconfig: base url is not set")
379+
if cfg.DefaultBaseURL != nil {
380+
cfg.BaseURL = cfg.DefaultBaseURL
381+
} else {
382+
return fmt.Errorf("requestconfig: base url is not set")
383+
}
377384
}
378385

379386
cfg.Request.URL, err = cfg.BaseURL.Parse(strings.TrimLeft(cfg.Request.URL.String(), "/"))
@@ -610,3 +617,17 @@ func PreRequestOptions(opts ...RequestOption) (RequestConfig, error) {
610617
}
611618
return cfg, nil
612619
}
620+
621+
// WithDefaultBaseURL returns a RequestOption that sets the client's default Base URL.
622+
// This is always overridden by setting a base URL with WithBaseURL.
623+
// WithBaseURL should be used instead of WithDefaultBaseURL except in internal code.
624+
func WithDefaultBaseURL(baseURL string) RequestOption {
625+
u, err := url.Parse(baseURL)
626+
return RequestOptionFunc(func(r *RequestConfig) error {
627+
if err != nil {
628+
return err
629+
}
630+
r.DefaultBaseURL = u
631+
return nil
632+
})
633+
}

option/requestoption.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ func WithRequestTimeout(dur time.Duration) RequestOption {
262262
// environment to be the "production" environment. An environment specifies which base URL
263263
// to use by default.
264264
func WithEnvironmentProduction() RequestOption {
265-
return WithBaseURL("https://api.openai.com/v1/")
265+
return requestconfig.WithDefaultBaseURL("https://api.openai.com/v1/")
266266
}
267267

268268
// WithAPIKey returns a RequestOption that sets the client setting "api_key".

0 commit comments

Comments
 (0)