为什么在开发服务器中,request.URL.Host和Scheme为空?

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

Why are request.URL.Host and Scheme blank in the development server?

问题

我对Go语言非常陌生。尝试了文档中的第一个hello, world示例,并想要从请求中读取主机和协议:

package hello

import (
    "fmt"
    "http"
)

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Host: " + r.URL.Host + " Scheme: " + r.URL.Scheme)
}

但它们的值都是空的。为什么呢?

英文:

I'm very new to Go. Tried this first hello, world from the documentation, and wanted to read the Host and Scheme from the request:

package hello

import (
    "fmt"
    "http"
)

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Host: " + r.URL.Host + " Scheme: " + r.URL.Scheme)
}

But their values are both blank. Why?

答案1

得分: 59

基本上,由于您从HTTP代理访问HTTP服务器,因此浏览器可以发出相对的HTTP请求,如下所示:

GET / HTTP/1.1
Host: localhost:8080

(当然,前提是服务器正在侦听本地主机的8080端口)。

现在,如果您使用代理访问该服务器,代理可能会使用绝对URL:

GET http://localhost:8080/ HTTP/1.1
Host: localhost:8080

在这两种情况下,从Go的http.Request.URL中获取的是原始URL(由库解析)。在您获取的情况下,您正在从相对路径访问URL,因此URL对象中缺少主机或方案。

如果您确实想获取HTTP主机,您可以访问http.Request结构的Host属性。请参阅http://golang.org/pkg/http/#Request

您可以使用netcat和适当格式的HTTP请求验证此操作(您可以复制上述代码块,在文件中确保后面有一个空行)。尝试一下:

cat my-http-request-file | nc localhost 8080

此外,您还可以通过调用IsAbs()方法在服务器/处理程序中检查请求中是否包含相对或绝对URL:

isAbsoluteURL := r.URL.IsAbs()
英文:

Basically, since you're accessing the HTTP server not from an HTTP proxy, a browser can issue a relative HTTP request, like so:

GET / HTTP/1.1
Host: localhost:8080

(Given that, of course, the server is listening on localhost port 8080).

Now, if you were accessing said server using a proxy, the proxy may use an absolute URL:

GET http://localhost:8080/ HTTP/1.1
Host: localhost:8080

In both cases, what you get from Go's http.Request.URL is the raw URL (as parsed by the library). In the case you're getting, you're accessing the URL from a relative path, hence the lack of a Host or Scheme in the URL object.

If you do want to get the HTTP host, you may want to access the Host attribute of the http.Request struct. See http://golang.org/pkg/http/#Request

You can validate that by using netcat and an appropriately formatted HTTP request (you can copy the above blocks, make sure there's a trailing blank line after in your file). To try it out:

cat my-http-request-file | nc localhost 8080

Additionally, you could check in the server/handler whether you get a relative or absolute URL in the request by calling the IsAbs() method:

isAbsoluteURL := r.URL.IsAbs()

huangapple
  • 本文由 发表于 2011年8月1日 21:26:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/6899069.html
匿名

发表评论

匿名网友

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

确定