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
+11.4k Golang : How to use if, eq and print properly in html template
+6k Golang : Use NLP to get sentences for each paragraph example
+22.8k Golang : Strings to lowercase and uppercase example
+9.7k Golang : How to generate Code 39 barcode?
+10.6k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+17.2k Golang : Capture stdout of a child process and act according to the result
+27.5k Golang : Convert CSV data to JSON format and save to file
+12.2k Golang : convert(cast) string to integer value
+11.3k Golang : Fix - does not implement sort.Interface (missing Len method)
+11.8k How to tell if a binary(executable) file or web application is built with Golang?
+4.5k Java : Generate multiplication table example
+13.6k Golang : Strings comparison