英文:
Golang 403 forbidden error
问题
当我尝试检查本地主机时,它返回正确的状态,但是当我尝试轮询网络上的一台机器时,它显示403-Forbidden错误。
package main
import "net/http"
import "fmt"
func main() {
resp, err := http.Get("http://site-centos-64:8080/examples/abc1.jsp")
fmt.Println(resp,err)
}
英文:
When I try to check a local host it returns the correct status but when I am trying to poll a machine on the network it shows 403-Forbidden error.
package main
import "net/http"
import "fmt"
func main() {
resp, err := http.Get("http://site-centos-64:8080/examples/abc1.jsp")
fmt.Println(resp,err)
}
答案1
得分: 1
根据你提供的内容,我给出以下翻译:
在不知道你的确切设置的情况下,我只能猜测,但通常这种情况发生在Web服务器对请求头进行过滤时。你可能需要添加一个Accept
和一个User-Agent
头部,以允许请求通过。
尝试类似以下的命令:
curl -i \
-H 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11' \
http://site-centos-64:8080/examples/abc1.jsp
如果这个命令有效,你可以在Go代码中使用Header.Add()方法设置这些头部。
package main
import "net/http"
import "fmt"
func main() {
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
req, err := http.NewRequest("GET", "http://site-centos-64:8080/examples/abc1.jsp", nil)
req.Header.Add("Accept", `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`)
req.Header.Add("User-Agent", `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11`)
resp, err := client.Do(req)
fmt.Println(resp,err)
}
上述curl命令修改自https://stackoverflow.com/questions/13294424/curl-http-1-1-403-forbidden-date的答案。
英文:
Without knowing the exact setup you're running, I can only guess, but this usually happens when the web server is filtering on request headers. You may need to add anAccept
and a User-Agent
header for the request to be allowed.
Try something like:
curl -i \
-H 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
-H 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11' \
http://site-centos-64:8080/examples/abc1.jsp
If this works, you can set these headers in the Go code using the Header.Add() method.
package main
import "net/http"
import "fmt"
func main() {
client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
req, err := http.NewRequest("GET", "http://site-centos-64:8080/examples/abc1.jsp", nil)
req.Header.Add("Accept", `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`)
req.Header.Add("User-Agent", `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11`)
resp, err := client.Do(req)
fmt.Println(resp,err)
}
The curl command above is modified from the answer to https://stackoverflow.com/questions/13294424/curl-http-1-1-403-forbidden-date .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论