🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
- Introduction
http.HeadFunction Syntax- Examples
- Basic Usage
- Checking Resource Availability
- Inspecting Response Headers
- Real-World Use Case Example
- 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.Headfunction sends a HEAD request tohttps://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.Headfunction checks if the resource athttps://example.com/nonexistentpageexists. - 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.Headfunction retrieves the headers fromhttps://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
validateURLfunction checks if a URL is accessible by sending a HEAD request. - It returns
trueif the status code is200 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment