How to execute a HEAD Request in GO?
Asked Answered
B

3

10

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.

Brainchild answered 25/7, 2016 at 8:49 Comment(1)
with curl, I think you can also use curl -I https://golang.org (reference: curl.haxx.se/docs/manpage.html#-I)Philpot
C
19

use http.Head()

res, err := http.Head("https://golang.org")
if err != nil {
    panic(err)
}
contentlength:=res.ContentLength
fmt.Printf("ContentLength:%v",contentlength)
Carmichael answered 25/7, 2016 at 8:50 Comment(1)
How to head request with a hostJumna
S
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

Sulemasulf answered 30/5, 2021 at 4:3 Comment(0)
T
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

Trotman answered 31/8, 2021 at 3:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.