Skip to content

Commit

Permalink
fix: context key conflict
Browse files Browse the repository at this point in the history
  • Loading branch information
shiroyk committed Dec 2, 2023
1 parent fcda11c commit 25a50b4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
8 changes: 4 additions & 4 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,20 @@ type Cache interface {
Del(ctx context.Context, key string)
}

var cacheTimeoutKey struct{}
type cacheTimeoutKey struct{}

// WithCacheTimeout returns the context with the cache timeout.
func WithCacheTimeout(ctx context.Context, timeout time.Duration) context.Context {
if c, ok := ctx.(*plugin.Context); ok {
c.SetValue(&cacheTimeoutKey, timeout)
c.SetValue(cacheTimeoutKey{}, timeout)
return ctx
}
return context.WithValue(ctx, &cacheTimeoutKey, timeout)
return context.WithValue(ctx, cacheTimeoutKey{}, timeout)
}

// CacheTimeout returns the context cache timeout value.
func CacheTimeout(ctx context.Context) time.Duration {
return cast.ToDuration(ctx.Value(&cacheTimeoutKey))
return cast.ToDuration(ctx.Value(cacheTimeoutKey{}))
}

// memoryCache is an implementation of Cache that stores bytes in in-memory.
Expand Down
18 changes: 10 additions & 8 deletions fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,29 @@ type Fetch interface {
Do(*http.Request) (*http.Response, error)
}

var requestProxyKey struct{}
type requestProxyKey struct{}

// WithProxyURL returns a copy of parent context in which the proxy associated with context.
func WithProxyURL(ctx context.Context, proxy *url.URL) context.Context {
if proxy == nil {
return ctx
}
if c, ok := ctx.(*plugin.Context); ok {
c.SetValue(&requestProxyKey, proxy)
c.SetValue(requestProxyKey{}, proxy)
return ctx
}
return context.WithValue(ctx, &requestProxyKey, proxy)
return context.WithValue(ctx, requestProxyKey{}, proxy)
}

// ProxyFromContext returns a proxy URL on context.
func ProxyFromContext(ctx context.Context) (*url.URL, error) {
if proxy := ctx.Value(&requestProxyKey); proxy != nil {
return proxy.(*url.URL), nil
func ProxyFromContext(ctx context.Context) *url.URL {
if proxy := ctx.Value(requestProxyKey{}); proxy != nil {
return proxy.(*url.URL)
}
return nil, nil
return nil
}

// ProxyFromRequest returns a proxy URL on request context.
func ProxyFromRequest(req *http.Request) (*url.URL, error) { return ProxyFromContext(req.Context()) }
func ProxyFromRequest(req *http.Request) (*url.URL, error) {
return ProxyFromContext(req.Context()), nil
}

0 comments on commit 25a50b4

Please sign in to comment.