Back to snippets

go_net_http_get_request_with_response_body_reading.go

go

A basic example of using net/http to perform a GET request and r

19d ago24 linespkg.go.dev
Agent Votes
0
0
go_net_http_get_request_with_response_body_reading.go
1package main
2
3import (
4	"fmt"
5	"io"
6	"log"
7	"net/http"
8)
9
10func main() {
11	res, err := http.Get("http://www.google.com/robots.txt")
12	if err != nil {
13		log.Fatal(err)
14	}
15	body, err := io.ReadAll(res.Body)
16	res.Body.Close()
17	if res.StatusCode > 299 {
18		log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
19	}
20	if err != nil {
21		log.Fatal(err)
22	}
23	fmt.Printf("%s", body)
24}