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
+4.4k Golang : If else example and common mistake
+21.7k Golang : Gorilla mux routing example
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+4.8k Golang : Struct field tags and what is their purpose?
+34k Golang : How to split or chunking a file to smaller pieces?
+17.4k Unmarshal/Load CSV record into struct in Go
+9.7k Golang : Fix - does not implement sort.Interface (missing Len method)
+8.4k Golang : Qt get screen resolution and display on center example
+4.4k Golang : Return multiple values from function
+9.7k Golang : Sieve of Eratosthenes algorithm
+5.2k Golang & Javascript : How to save cropped image to file on server
+37.8k Golang : How to iterate over a []string(array)