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
+6.8k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+19.4k Golang : Archive directory with tar and gzip
+10.7k Golang : Simple image viewer with Go-GTK
+10.8k Golang : How to determine a prime number?
+8.5k Golang : Executing and evaluating nested loop in html template
+5.8k Golang : Create new color from command line parameters
+3.4k Golang : Switch Redis database redis.NewClient
+30.1k Get client IP Address in Go
+13.7k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+6.1k PHP : Proper way to get UTF-8 character or string length
+36.1k Golang : Convert date or time stamp from string to time.Time type
+7k Golang : How to iterate a slice without using for loop?