Skip to content

Instantly share code, notes, and snippets.

@ironcladlou
Created July 16, 2019 18:00
Show Gist options
  • Save ironcladlou/dd1e05301d15534aa2887639c05f03a0 to your computer and use it in GitHub Desktop.
Save ironcladlou/dd1e05301d15534aa2887639c05f03a0 to your computer and use it in GitHub Desktop.
package main
import (
"os"
"fmt"
"net/http"
"net/url"
)
/*
Examples:
$ go run proxy.go
proxy: <nil>
proxy: <nil>
$ HTTP_PROXY=localhost:1234 go run proxy.go
proxy: http://localhost:1234
proxy: http://localhost:1234
*/
func main() {
// The default transport many libraries use internally indirectly
// via http.DefaultClient. Notice that the Proxy field is stateful
// and guarded by a sync.Once:
// https://golang.org/src/net/http/transport.go
transport := http.DefaultTransport.(*http.Transport)
parsedURL, _:= url.Parse("http://example.com")
// The first request to flow through DefaultTransport will cause
// the Proxy field to be set based on the environment at the current
// execution point.
request := &http.Request{URL: parsedURL}
proxiedURL, _ := transport.Proxy(request)
fmt.Printf("proxy: %s\n", proxiedURL)
// Setting the environment now has no effect on the Proxy function
// already assigned to DefaultTransport.
os.Setenv("HTTP_PROXY", "localhost")
request = &http.Request{URL: parsedURL}
proxiedURL, _ = transport.Proxy(request)
fmt.Printf("proxy: %s\n", proxiedURL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment