8

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.

  • 1
    with curl, I think you can also use `curl -I https://golang.org` (reference: https://curl.haxx.se/docs/manpage.html#-I) – dmitris Jul 25 '16 at 11:53

3 Answers3

17

use http.Head()

res, err := http.Head("https://golang.org")
if err != nil {
    panic(err)
}
contentlength:=res.ContentLength
fmt.Printf("ContentLength:%v",contentlength)
Said Saifi
  • 1,995
  • 7
  • 26
  • 45
1

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

hookenz
  • 36,432
  • 45
  • 177
  • 286
0

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

Zombo
  • 1
  • 62
  • 391
  • 407