Skip to main content
The Go standard library comes with excellent support for HTTP clients and servers in the net/http package. This example demonstrates how to issue simple HTTP requests.

Basic HTTP GET Request

The simplest way to make an HTTP request is using http.Get, which is a convenient shortcut around creating an http.Client object.
package main

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

func main() {
	// Issue an HTTP GET request to a server. `http.Get` is a
	// convenient shortcut around creating an `http.Client`
	// object and calling its `Get` method; it uses the
	// `http.DefaultClient` object which has useful default
	// settings.
	resp, err := http.Get("https://gobyexample.com")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	// Print the HTTP response status.
	fmt.Println("Response status:", resp.Status)

	// Print the first 5 lines of the response body.
	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)
	}
}

Key Concepts

The http.Get function uses the default HTTP client which has sensible default settings for timeouts, redirects, and connection pooling.
Always remember to close the response body with defer resp.Body.Close() to prevent resource leaks.
HTTP requests can fail for many reasons (network issues, DNS problems, etc.), so always check for errors returned by http.Get.

Running the Example

$ go run http-clients.go
Response status: 200 OK
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Go by Example</title>
The example prints the HTTP status code and the first 5 lines of the response body.

Next Steps

HTTP Server

Learn how to build HTTP servers in Go

Context

Control request cancellation with context

Build docs developers (and LLMs) love