I want to get the content length of a page using GO net/http? I can do this in terminal using curl -i -X HEAD https://golang.org
and then check the content-length field.
How to execute a HEAD Request in GO?
use http.Head()
res, err := http.Head("https://golang.org")
if err != nil {
panic(err)
}
contentlength:=res.ContentLength
fmt.Printf("ContentLength:%v",contentlength)
How to head request with a host –
Jumna
Another option:
package main
import "net/http"
func main() {
req, e := http.NewRequest("HEAD", "https://stackoverflow.com", nil)
if e != nil {
panic(e)
}
res, e := new(http.Client).Do(req)
if e != nil {
panic(e)
}
println(res.StatusCode == 200)
}
With timeouts
package main
import (
"net/http"
"os"
"fmt"
"time"
)
func main() {
var client = &http.Client{
Timeout: time.Second * 10,
}
res, err := client.Head("https://stackoverflow.com")
if err != nil {
if os.IsTimeout(err) {
// timeout
panic(err)
} else {
panic(err)
}
}
fmt.Println("Status:", res.StatusCode)
fmt.Println("ContentLength:", res.ContentLength)
}
© 2022 - 2024 — McMap. All rights reserved.
curl -I https://golang.org
(reference: curl.haxx.se/docs/manpage.html#-I) – Philpot