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.3k Golang : Convert date string to variants of time.Time type examples
+5k Golang *File points to a file or directory ?
+15.4k Golang : Read large file with bufio.Scanner cause token too long error
+33.4k Golang : convert(cast) bytes to string
+23.6k Golang : Find biggest/largest number in array
+7.2k SSL : How to check if current certificate is sha1 or sha2 from command line
+17.1k Golang : [json: cannot unmarshal object into Go value of type]
+62.2k Golang : Convert HTTP Response body to string
+17.5k Golang : How to remove certain lines from a file
+19.4k Golang : Convert seconds to human readable time format example
+4.4k PHP : Extract part of a string starting from the middle
+18.1k Golang : Set, Get and List environment variables