Golang : Convert HTTP Response body to string
Problem :
While writing tutorial on how to interface with PayPal's IPN(Instant Payment Notification), I need to convert the HTTP Response body to string for verifying the IPN. So how to convert the response body to string ?
Solution :
Use ioutil.ReadAll(resp.Body)
function to read all the body and convert to string with string()
function.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
resp, err := http.Get("https://golang.org")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer resp.Body.Close()
htmlData, err := ioutil.ReadAll(resp.Body) //<--- here!
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// print out
fmt.Println(os.Stdout, string(htmlData)) //<-- here !
// use Regular Expression to search for keyword
// for example
verified, err := regexp.MatchString("VERIFIED", string(htmlData))
//if err != nil {
// fmt.Println(err)
// return
// }
}
See also : Golang : Interfacing with PayPal's IPN(Instant Payment Notification) 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
+5k PHP : Hide PHP version information from curl
+14.5k Golang : How to check for empty array string or string?
+7.2k Golang : Rename part of filename
+22.6k Golang : Randomly pick an item from a slice/array example
+24.8k Golang : Convert uint value to string type
+11k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+7.7k Android Studio : Rating bar example
+7.2k SSL : How to check if current certificate is sha1 or sha2 from command line
+19.4k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+13.6k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+8.1k Golang : How to check variable or object type during runtime?
+6.2k Unix/Linux : How to get own IP address ?