Skip to content

Instantly share code, notes, and snippets.

@icexin
Last active December 31, 2023 11:53
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save icexin/f3c77f17dcc28e5f43c8cdcc4e88e9da to your computer and use it in GitHub Desktop.
Save icexin/f3c77f17dcc28e5f43c8cdcc4e88e9da to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"net/http"
"net/url"
)
type contextKey int
const (
proxyURLKey contextKey = 0
)
func proxy(req *http.Request) (*url.URL, error) {
iproxy := req.Context().Value(proxyURLKey)
if iproxy == nil {
fmt.Printf("no proxy found\n")
return nil, nil
}
proxyURL := iproxy.(*url.URL)
fmt.Printf("proxy found:%s\n", proxyURL.String())
return proxyURL, nil
}
func main() {
transport := &http.Transport{
Proxy: proxy,
}
client := http.Client{
Transport: transport,
}
{
proxyURL, _ := url.Parse("http://127.0.0.1:8000")
ctx := context.WithValue(context.Background(), proxyURLKey, proxyURL)
requestWithProxy, err := http.NewRequestWithContext(ctx, "GET", "http://www.baidu.com", nil)
if err != nil {
panic(err)
}
client.Do(requestWithProxy)
}
{
requestWithoutProxy, err := http.NewRequest("GET", "http://www.baidu.com", nil)
if err != nil {
panic(err)
}
client.Do(requestWithoutProxy)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment