Created
March 5, 2018 18:09
-
-
Save jesvs/86ae4713b8f9f8808b55408bc92b6297 to your computer and use it in GitHub Desktop.
Golang: Change the proxy net/http uses during execution.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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