Go HTTP client minimal example
This example gets the current IPv4 address from TechOverflow’s IP address HTTP API How to get your current IPv4 address using wget.
package main
import (
"io/ioutil"
"net/http"
)
func main() {
// Perform request
resp, err := http.Get("https://ipv4.techoverflow.net/api/get-my-ip")
if err != nil {
print(err)
return
}
// Cleanup when this function ends
defer resp.Body.Close()
// Read all the response data into a []byte
body, err := ioutil.ReadAll(resp.Body)
// Decode & print
println(string(body))
}
Save as Main.go
in a new project directory (e.g. GoHttpTest
) and run go build
in that directory.
After that, you can run ./GoHttpTest which should print your IPv4 adress. Example:
uli@server ~/GoHttpTest % go build
uli@server ~/GoHttpTest % ./GoHttpTest
91.59.80.56