Making Tor HTTP Requests with Go

Advertisement

Advertisement

Go provides standard packages for working with HTTP, URLs, and proxies. Below is an example of how to make an HTTP request using a Tor proxy with the Go programming language. The key difference from making a standard HTTP request is that you must configure the HTTP client to use the proxy. This is done by creating a proxy dialer, creating an HTTP transport that uses that proxy dialer, and then creating an HTTP client that uses that transport. Check out the example below.

If you do not already have Tor setup, you can follow these instructions for setting up Tor in Linux or download the Tor Browser Bundle.

package main

import (
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)

// URL to fetch
var webUrl string = "https://check.torproject.org"

// Specify Tor proxy ip and port
var torProxy string = "socks5://127.0.0.1:9050" // 9150 w/ Tor Browser

func main() {
// Parse Tor proxy URL string to a URL type
torProxyUrl, err := url.Parse(torProxy)
if err != nil {
log.Fatal("Error parsing Tor proxy URL:", torProxy, ".", err)
}

// Set up a custom HTTP transport to use the proxy and create the client
torTransport := &http.Transport{Proxy: http.ProxyURL(torProxyUrl)}
client := &http.Client{Transport: torTransport, Timeout: time.Second * 5}

// Make request
resp, err := client.Get(webUrl)
if err != nil {
log.Fatal("Error making GET request.", err)
}
defer resp.Body.Close()

// Read response
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("Error reading body of response.", err)
}
log.Println(string(body))
log.Println("Return status code:", resp.StatusCode)
}

Reference

Advertisement

Advertisement