Skip to content

Instantly share code, notes, and snippets.

@prasincs
Created May 14, 2017 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prasincs/1b02bc58d5688916f79f7ffc9d933826 to your computer and use it in GitHub Desktop.
Save prasincs/1b02bc58d5688916f79f7ffc9d933826 to your computer and use it in GitHub Desktop.
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