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:
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!
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.