我想使用GO net/http获取页面的内容长度?在终端中,我可以使用
curl -i -X HEAD https://golang.org
命令来检查content-length字段。res, err := http.Head("https://golang.org")
if err != nil {
panic(err)
}
contentlength:=res.ContentLength
fmt.Printf("ContentLength:%v",contentlength)
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)
}
另一个选项:
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)
}
curl -I https://golang.org
(参考:https://curl.haxx.se/docs/manpage.html#-I)。 - dmitris