doubo1871 2011-08-01 13:26
浏览 468
已采纳

为什么开发服务器中的request.URL.Host和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条回答 默认 最新

  • doudu4282 2011-08-02 11:55
    关注

    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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?