Reputation:
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.
Upvotes: 10
Views: 10076
Reputation: 38967
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)
}
https://play.golang.org/p/5UAA-PUyoZc
Upvotes: 1
Reputation: 1
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)
}
https://golang.org/pkg/net/http#NewRequest
Upvotes: 1
Reputation: 2408
use http.Head()
res, err := http.Head("https://golang.org")
if err != nil {
panic(err)
}
contentlength:=res.ContentLength
fmt.Printf("ContentLength:%v",contentlength)
Upvotes: 19