Golang : Get curl -I or head data from URL example
Problem :
Need a way to make a HEAD request from URL and extract a few fields of header data from the response.
Solution :
A HEAD request is similar to curl -I
command and in Golang, the similar task can be achieved with the net/http.Head()
function.
Here is an example of HEAD request in Golang :
package main
import (
"fmt"
"net/http"
)
func main() {
resp, err := http.Head("http://www.golang.org")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(resp)
// you can isolate the data further
// READ http://golang.org/pkg/net/http/#Response
contentLength := resp.ContentLength
fmt.Println("Content Length : ", contentLength)
}
and the output :
&{200 OK 200 HTTP/1.1 1 1 map[Content-Type:[text/html; charset=utf-8] Date:[Mon, 20 Jul 2015 09:02:28 GMT] Server:[Google Frontend]
Content-Length:[7537] Alternate-Protocol:[80:quic,p=0]] 0xc208054500 7537 [] false map[] 0xc208032750
} Content Length : 7537
and compare the output to curl -I
command.
>curl -I https://www.golang.org
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Mon, 20 Jul 2015 08:54:37 GMT
Server: Google Frontend
Content-Length: 7537
Alternate-Protocol: 443:quic,p=1
References :
See also : Golang : Set or Add HTTP Request Headers
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+20.8k Golang : For loop continue,break and range
+7.2k Golang : Create zip/ePub file without compression(use Store algorithm)
+10.2k Golang : Generate random integer or float number
+4.7k Python : Find out the variable type and determine the type with simple test
+7.5k Golang : Example of how to detect which type of script a word belongs to
+22.7k Golang : Test file read write permission example
+11.9k Golang : Split strings into command line arguments
+8.2k Golang : How to check variable or object type during runtime?
+6.5k Golang : Check if password length meet the requirement
+5.7k Golang : Extract unicode string from another unicode string example
+23.7k Golang : Upload to S3 with official aws-sdk-go package
+7k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream