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
+3.7k JavaScript: Add marker function on Google Map
+6.8k Golang : get the current working directory of a running program
+11.7k Generate salted password with OpenSSL example
+16.2k Golang : How to remove certain lines from a file
+11.9k Golang : Handle or parse date string with Z suffix(RFC3339) example
+3.9k Golang : Customize scanner.Scanner to treat dash as part of identifier
+17.3k Golang : Padding data for encryption and un-padding data for decryption
+27.8k Golang : Save map/struct to JSON or XML file
+15.4k CodeIgniter/PHP : Create directory if does not exist example
+16.2k Golang : Clone with pointer and modify value
+6.8k Golang : Get today's weekday name and calculate target day distance example
+6.5k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image