make a http head request in go

To make an HTTP HEAD request in Go, we can use the standard library's http package. Here's how to do it:

main.go
package main

import (
    "fmt"
    "net/http"
)

func main() {
    url := "https://example.com"
    req, err := http.NewRequest("HEAD", url, nil)
    if err != nil {
        fmt.Println("Error creating HTTP request:", err)
        return
    }
    client := http.DefaultClient
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error making HTTP request:", err)
        return
    }
    defer resp.Body.Close()
    // Do something with the response here
    fmt.Println("Response status:", resp.Status)
}
529 chars
25 lines

In this code, we first create a new http.Request object using the http.NewRequest function, passing in the HTTP method (HEAD), the URL to request, and an optional request body (which we don't need for a HEAD request).

We then use the http.DefaultClient to perform the request using the client.Do(req) method. This returns an http.Response object that we can inspect for the result of our request.

Finally, we close the response body using defer resp.Body.Close(), and then do something with the response (in this case, print out the response status).

related categories

gistlibby LogSnag