2016-11-27 152 views
2

在Ruby/Rack中,我能夠get the scheme of the current request URL from scheme#request。然而,在圍棋,http.Request.URL.Scheme返回一個空字符串:獲取當前請求URL的方案

package main 

import (
    "fmt" 
    "log" 
    "net/http" 
) 

func main() { 
    http.HandleFunc("/", handler) 
    log.Fatal(http.ListenAndServe(":8080", nil)) 
} 

func handler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "%#v\n", r.URL.Scheme) // Always shows empty string 
} 

我怎樣才能把當前請求的URL的方案?

+0

您可以檢查'r.Proto'它將返回HTTP/1.1或HTTP/2文件,但不知道它是否會爲HTTPS –

回答

-1

這是因爲,你所訪問HTTP服務器這樣:

GET/HTTP/1.1 
Host: localhost:8080 
在這種情況下

的基礎上,分析你得到的是來自Go的http.Request.URL原始URL。爲什麼你得到這個是因爲你從一個相對路徑訪問URL,因此缺少URL對象中的主機或方案。

如果您確實想要獲取HTTP主機,則可能必須訪問http.Request結構的Host屬性。見http://golang.org/pkg/http/#Request

,因爲它是不能直接使用,但你仍然可以能夠組裝起來:

u := r.URL 

// The scheme can be http/https because that's depends on protocol your server handles. 
u.Scheme = "http" 
+0

http://stackoverflow.com/根據變化問題/ 6899069/why-are-request-url-host-and-scheme-blank-in-the-development-server從舊的答案中複製。 – I159

2

本地主機是URL形成一種特殊情況。無論如何,如果你的客戶端是本地主機,它將是空的。

net.http package doc

作爲一個特殊的情況下,如果是req.URL.Host「本地主機」(具有或不具有端口號),然後將返回一個零URL和零誤差。

獲取所需url/uri信息的方法是直接從http.Request獲取。例如:

func handler(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "%s\n", r.Host)      
}