Skip to content

Instantly share code, notes, and snippets.

@LuD1161
Created June 22, 2022 05:32
Show Gist options
  • Save LuD1161/25e40b28e6cb1141caaf8e2189cce1e8 to your computer and use it in GitHub Desktop.
Save LuD1161/25e40b28e6cb1141caaf8e2189cce1e8 to your computer and use it in GitHub Desktop.
HTTP Request with Custom DNS Resolver & Transport
package main
import (
"context"
"crypto/tls"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"time"
)
func main() {
customDialContext := CustomDialContext("1.1.1.1:53") // Enter your DNS IP here with port, default 53
customTransport := SetProxyTransport(customDialContext)
client := &http.Client{Transport: customTransport}
URL := "http://aseemshrey.in"
resp, err := client.Get(URL)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
log.Println(string(body))
}
func SetProxyTransport(dialContext func(ctx context.Context, network string, addr string) (net.Conn, error)) *http.Transport {
// create proxy transport
proxyURL := os.Getenv("PROXY_URL")
// Allow insecure, expired certificates
proxyTransport := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, DialContext: dialContext}
if proxyURL != "" {
proxy, err := url.Parse(proxyURL)
if err != nil {
log.Printf("Error in parsing PROXY_URL from env vars, going with no proxy : %s", err.Error())
}
proxyTransport.Proxy = http.ProxyURL(proxy)
log.Printf("Proxy set in http.transport : %s", proxyURL)
} else {
log.Printf("PROXY_URL empty. Hence, no proxy set in http.transport.")
}
return proxyTransport
}
func CustomDialContext(dns string) func(ctx context.Context, network string, addr string) (net.Conn, error) {
var (
dnsResolverIP = dns // Google DNS resolver.
dnsResolverProto = "udp" // Protocol to use for the DNS resolver
dnsResolverTimeoutMs = 5000 // Timeout (ms) for the DNS resolver (optional)
)
dialer := &net.Dialer{
Resolver: &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: time.Duration(dnsResolverTimeoutMs) * time.Millisecond,
}
return d.DialContext(ctx, dnsResolverProto, dnsResolverIP)
},
},
}
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, network, addr)
}
return dialContext
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment