How to check if a web file exists or not by using golang?

huangapple go评论74阅读模式
英文:

How to check if a web file exists or not by using golang?

问题

我想检查一个大文件是否存在于一个 Web 服务器上,使用的是 Go 语言:

resp, err := http.Get("http://aa.com/aa.mp4")
if err != nil {
   return false
}
if resp.StatusCode != http.StatusOK {
	return false
}

我可以得到我想要的结果,但是 aa.mp4 是一个大文件,所以这种方式看起来不太理想。是否有其他方法?

英文:

I want to check if a large file exists on a web server using golang :

resp, err := http.Get("http://aa.com/aa.mp4")
if err != nil {
   return false
  }
if resp.StatusCode != http.StatusOK {
	return false
}

I can get what i want, but the aa.mp4 is a large file, so this way looks nonoptimal. Is there another way?

答案1

得分: 8

你可以使用HEAD请求代替http.Head()

它与GET请求相同,但不会下载响应体。

resp, err := http.Head("http://aa.com/aa.mp4")
if err != nil {
    return false
}
if resp.StatusCode != http.StatusOK {
    return false
}

根据HTTP规范:

HEAD方法与GET方法相同,但服务器在响应中不返回消息体。

英文:

You can do a HEAD request instead http.Head()

It is the same as a GET but won't download the body.

resp, err := http.Head("http://aa.com/aa.mp4")
  if err != nil {
   return false
  }
  if resp.StatusCode != http.StatusOK {
    return false
  }

From the HTTP spec:

> The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response

huangapple
  • 本文由 发表于 2017年3月9日 17:45:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/42691856.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定