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 JQuery : Calling a function inside Jquery(document) block
+16.5k Golang : Send email and SMTP configuration example
+4.7k JavaScript : Rounding number to decimal formats to display currency
+8.1k Findstr command the Grep equivalent for Windows
+27k Golang : Force your program to run with root permissions
+19k Golang : Read input from console line
+6.5k Golang : Break string into a slice of characters example
+9.3k Golang : Generate Codabar
+12.4k Golang : Print UTF-8 fonts on image example
+15.3k Golang : Get HTTP protocol version example
+25.5k Golang : Convert long hexadecimal with strconv.ParseUint example
+15.8k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type