Golang http Head Function

Golang http.Head Function

The http.Head function in Golang is part of the net/http package and is used to send an HTTP HEAD request to a specified URL. Unlike http.Get, it retrieves only the response headers without downloading the response body. This method is useful for checking the existence of a resource, inspecting metadata, or verifying links without downloading the actual content.

Table of Contents

  1. Introduction
  2. http.Head Function Syntax
  3. Examples
    • Basic Usage
    • Checking Resource Availability
    • Inspecting Response Headers
  4. Real-World Use Case Example
  5. Conclusion

Introduction

The http.Head function allows you to send an HTTP HEAD request to a URL and retrieve the response headers without downloading the body. This is useful when you need to check the status or metadata of a resource without transferring the entire content.

http.Head Function Syntax

The syntax for the http.Head function is as follows:

func Head(url string) (resp *http.Response, err error)

Parameters:

  • url: A string specifying the URL to which the HEAD request is sent.

Returns:

  • *http.Response: A pointer to the HTTP response received from the server.
  • error: An error value, which is non-nil if the request fails.

Examples

Basic Usage

This example demonstrates how to use http.Head to make a simple HEAD request.

Example

package main

import (
	"fmt"
	"net/http"
)

func main() {
	resp, err := http.Head("https://example.com")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	fmt.Println("Response Status:", resp.Status)
}

Explanation:

  • The http.Head function sends a HEAD request to https://example.com.
  • The response status is printed to the console.

Checking Resource Availability

This example shows how to use http.Head to check if a resource exists at a given URL.

Example

package main

import (
	"fmt"
	"net/http"
)

func main() {
	resp, err := http.Head("https://example.com/nonexistentpage")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusOK {
		fmt.Println("Resource exists.")
	} else {
		fmt.Printf("Resource does not exist. Status code: %d\n", resp.StatusCode)
	}
}

Explanation:

  • The http.Head function checks if the resource at https://example.com/nonexistentpage exists.
  • If the status code is 200 OK, the resource exists. Otherwise, a message indicates that the resource does not exist.

Inspecting Response Headers

This example demonstrates how to inspect the headers of a response without downloading the body.

Example

package main

import (
	"fmt"
	"net/http"
)

func main() {
	resp, err := http.Head("https://example.com")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	for key, value := range resp.Header {
		fmt.Printf("%s: %s\n", key, value)
	}
}

Explanation:

  • The http.Head function retrieves the headers from https://example.com.
  • The headers are printed to the console.

Real-World Use Case Example: Validating a URL

In a real-world scenario, you might use http.Head to validate the availability of a URL before performing further actions, such as downloading or linking to the resource.

Example: URL Validation

package main

import (
	"fmt"
	"net/http"
)

func validateURL(url string) bool {
	resp, err := http.Head(url)
	if err != nil {
		fmt.Println("Error:", err)
		return false
	}
	defer resp.Body.Close()

	return resp.StatusCode == http.StatusOK
}

func main() {
	url := "https://example.com"
	if validateURL(url) {
		fmt.Println("URL is valid and accessible.")
	} else {
		fmt.Println("URL is not accessible.")
	}
}

Explanation:

  • The validateURL function checks if a URL is accessible by sending a HEAD request.
  • It returns true if the status code is 200 OK, indicating that the URL is valid and accessible.

Conclusion

The http.Head function in Go is useful for checking the status or metadata of a resource without downloading the entire content. It is a practical tool for tasks like validating URLs, inspecting response headers, and ensuring the availability of resources before performing further actions.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare