[Go]HTTP client and read the contents of a http body

This is a simple program that gets the response body of google.com. The response is returned and stored in resp, then ioutil.ReadAll() reads resp.Body. The resp.Body will then be converted into string and output by fmt.Println.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

func main() {
	resp, err := http.Get("http://google.com")
	// error handling
	if err != nil {
		log.Fatal(err)
	}

	// ioutil.ReadAll returns a byte slice and an error.
	// b is the byte slice which holds the content in resp.Body.
	b, e := ioutil.ReadAll(resp.Body)
	// error handling
	if e!= nil {
		log.Fatal(e)
	}
	// Print out the output with unwanted spaces trimmed.
	fmt.Println(strings.TrimSpace(string(b)))
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s