Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error when making HTTP GET request in Go: "dial tcp: lookup api.ipify.org on [::1]:53: read udp [::1]:50975->[::1]:53: read: connection refused"

I’m trying to make an HTTP GET request in Go using the net/http package to retrieve my public IP address using the api.ipify.org service. I’m encountering an error only after I build the application using the following command:

CGO_ENABLED=0 GOOS=linux go build -a -ldflags "-s -w" -o ip get.go

However, I noticed that the code works perfectly fine when I use either of the following commands:

go build get.go
go run get.go

Here’s the code I’m using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func get() {
    resp, err := http.Get("https://api.ipify.org")
    if err == nil {
        defer resp.Body.Close()
        bodyBytes, _ := ioutil.ReadAll(resp.Body)
        body := string(bodyBytes)
        fmt.Println(body)
    } else {
        fmt.Println(err)
    }
}

func main() {
    get()
}

It’s perplexing to me why the code works with go build and go run but fails when I use the more complex build command. Could someone please help me understand what might be causing this issue and how I can resolve it? Thank you for your time and assistance!

>Solution :

When cgo is available, the cgo-based resolver is used. It uses various way to resolve the domain that is reading /etc/resolv.conf or /etc/nsswitch.conf, etc. These features are not implemented by Go based DNS resolver therefore resulting in failure to resolve the domain and HTTP request fails.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading