Created
May 14, 2017 04:36
-
-
Save prasincs/1b02bc58d5688916f79f7ffc9d933826 to your computer and use it in GitHub Desktop.
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" | |
"os" | |
"golang.org/x/net/proxy" | |
) | |
func ProxyAwareHttpClient() *http.Client { | |
// sane default | |
var dialer proxy.Dialer | |
// eh, I want the type to be proxy.Dialer but assigning proxy.Direct makes the type proxy.direct | |
dialer = proxy.Direct | |
proxyServer, isSet := os.LookupEnv("HTTP_PROXY") | |
if isSet { | |
proxyUrl, err := url.Parse(proxyServer) | |
if err != nil { | |
fmt.FPrintf(os.Stderr, "Invalid proxy url %q\n", proxyUrl) | |
} | |
dialer, err = proxy.FromURL(proxyUrl, proxy.Direct) | |
} | |
// setup a http client | |
httpTransport := &http.Transport{} | |
httpClient := &http.Client{Transport: httpTransport} | |
httpTransport.Dial = dialer.Dial | |
return httpClient | |
} | |
func main() { | |
req, err := http.NewRequest("GET", "http://google.com", nil) | |
if err != nil { | |
panic(err) | |
} | |
client := proxyAwareHttpClient() | |
res, err := client.Do(req) | |
if err != nil { | |
panic(err) | |
} | |
defer res.Body.Close() | |
contents, err := ioutil.ReadAll(res.Body) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(contents) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment