Skip to content

Instantly share code, notes, and snippets.

@jesvs
Created March 5, 2018 18:09
Show Gist options
  • Save jesvs/86ae4713b8f9f8808b55408bc92b6297 to your computer and use it in GitHub Desktop.
Save jesvs/86ae4713b8f9f8808b55408bc92b6297 to your computer and use it in GitHub Desktop.
Golang: Change the proxy net/http uses during execution.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
// Go's net/http gets (and caches) the environment variable HTTP_PROXY
// to use as a proxy for all its communications.
// If you try os.Setenv("HTTP_PROXY", "newproxyserver:8080") you'll
// notice that it won't change due to net/http caching the initial value.
// This is how to change the proxy during execution.
func main() {
proxyURL, _ := url.Parse("http://proxyserver:80")
client := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
resp, err := client.Get("http://example.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Print(string(bs[:]))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment