Go by Example: HTTP Client

package main

import (
	"bufio"
	"fmt"
	"net/http"
)

func main() {
	resp, err := http.Get("http://www.google.com")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("Response status:", resp.Status)
	scanner := bufio.NewScanner(resp.Body)
	for i := 0; scanner.Scan() && i < 5; i++ {
		fmt.Println(scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		panic(err)
	}
}

This example uses the http package’s Get function to make a GET request to http://www.google.com. The Response struct returned by Get contains the response status, headers, and body. The body is read using a bufio.Scanner and the first 5 lines are printed out. The defer statement is used to ensure that the response body is properly closed after reading.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *