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
+11.9k Golang : Split strings into command line arguments
+19.7k Golang : Reset or rewind io.Reader or io.Writer
+4.9k Golang : Print instead of building pyramids
+20.4k Golang : Convert date string to variants of time.Time type examples
+20.5k Golang : Underscore or snake_case to camel case example
+7.5k Golang : Test if an input is an Armstrong number example
+13.8k Javascript : Prompt confirmation before exit
+11.4k Golang : How to detect a server/machine network interface capabilities?
+8.7k Golang : automatically figure out array length(size) with three dots
+10.9k Golang : Fix - does not implement sort.Interface (missing Len method)
+16.7k Golang : Get number of CPU cores