Golang : Set up source IP address before making HTTP request
Problem :
There are times that you want to use certain IP address in a machine ( such as the one with permission to connect outside a firewall ) before making a HTTP request to another server. This is similar to the wget binding command :
For example : wget --bind-address=192.168.10.1 \
How to do that in Golang?
NOTE : This is not for masking or spoofing your IP address
Solution :
Build your own custom HTTP transport client and specify the local IP address that has the permission to connect outside a firewall.
For example :
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"time"
)
func main() {
OKAddr := "<change here>" // local IP address to use
OKAddress, _ := net.ResolveTCPAddr("tcp", OKAddr)
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
OKAddr: OKAddress}).Dial, TLSHandshakeTimeout: 10 * time.Second}
client := &http.Client{
Transport: transport,
}
resp, err := client.Get("http://example.com/filetodown.zip")
if err != nil {
panic(err)
}
defer resp.Body.Close()
html, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
// fmt.Println(os.Stdout, string(html))
// or save the zip - see https://www.socketloop.com/tutorials/golang-download-file-example
}
References :
https://www.socketloop.com/tutorials/golang-convert-http-response-body-to-string
https://www.socketloop.com/tutorials/golang-download-file-example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.9k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+19.5k Golang : Set or Add HTTP Request Headers
+7.5k Golang : Command line ticker to show work in progress
+21.4k Golang : Encrypt and decrypt data with TripleDES
+8.3k PHP : How to parse ElasticSearch JSON ?
+13.6k Golang : How to determine if a year is leap year?
+14.9k Golang : Search folders for file recursively with wildcard support
+5.9k Golang : Grab news article text and use NLP to get each paragraph's sentences
+16.3k Golang : Execute terminal command to remote machine example
+13k Golang : How to calculate the distance between two coordinates using Haversine formula
+20k Golang : How to get own program name during runtime ?
+7.9k Golang : Check from web if Go application is running or not