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
+39.4k Golang : Remove dashes(or any character) from string
+6.4k Golang : Map within a map example
+11.5k Golang : Simple file scaning and remove virus example
+11.4k CodeIgniter : Import Linkedin data
+29.1k Golang : missing Git command
+12.8k Golang : Get terminal width and height example
+13.1k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+8.1k Golang : Reverse text lines or flip line order example
+31.9k Golang : Validate email address with regular expression
+5.1k Golang : Print instead of building pyramids
+32.1k Golang : Math pow(the power of x^y) example