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
+10.1k Golang : Turn string or text file into slice example
+11.5k Golang : Characters limiter example
+8.1k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+10.3k Golang : Identifying Golang HTTP client request
+13.3k Golang : How to get a user home directory path?
+18.3k Golang : Convert IPv4 address to decimal number(base 10) or integer
+14.2k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+9.9k Golang : Qt get screen resolution and display on center example
+11.4k Golang : How to pipe input data to executing child process?
+16k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+25.9k Golang : How to write CSV data to file
+10.4k Golang : How to get quoted string into another string?