Search⌘ K
AI Features

Polling Websites and Reading Web Page

Explore how to send HTTP requests to poll websites and read web page content using Go's net/http package. Learn to handle errors, interpret HTTP status codes, and work with response headers. This lesson prepares you to build simple web applications by mastering essential web communication techniques in Go.

We'll cover the following...

Introduction

Sending a website a very simple request and seeing how the website responds is known as polling a website.

Explanation

Consider the following example where a request includes only an HTTP header.

Go (1.6.2)
package main
import (
"fmt"
"net/http"
)
var urls = []string{
"http://www.google.com/",
"http://golang.org/",
"http://blog.golang.org/",
}
func main() {
// Executes an HTTP HEAD request for all URL's
// and returns the HTTP status string or an error string.
for _, url := range urls {
resp, err := http.Head(url)
if err != nil {
fmt.Println("Error:", url, err)
}
fmt.Println(url, ": ", resp.Status)
}
}

In the program above:

  • Line 4: We import the package net/http.
  • Lines 7-11: All URLs defined in an array of strings urls are polled.
  • Lines 16-22: We start an iteration over urls with a for-range loop.
    • Line 17: A simple http.Head() request is sent to each url to see how they react. The function’s signature is: func Head(url string) (r *Response, err
...