【问题标题】:How to execute a HEAD Request in GO?如何在 GO 中执行 HEAD 请求?
【发布时间】:2016-07-25 08:49:23
【问题描述】:

我想使用 GO net/http 获取页面的内容长度?我可以使用curl -i -X HEAD https://golang.org 在终端中执行此操作,然后检查内容长度字段。

【问题讨论】:

标签: http go net-http


【解决方案1】:

使用http.Head()

res, err := http.Head("https://golang.org")
if err != nil {
    panic(err)
}
contentlength:=res.ContentLength
fmt.Printf("ContentLength:%v",contentlength)

【讨论】:

  • 如何向主机发送请求
【解决方案2】:

另一种选择:

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

【讨论】:

    【解决方案3】:

    有超时

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-13
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 2019-10-20
      • 2011-12-11
      • 2010-09-11
      相关资源
      最近更新 更多