2016-03-13 68 views
-1

This answer關於static to static(file:// - > file://)聲明webserver(http://)可用於在不違反CORS的情況下將文件提供給本地靜態頁面(file://)。並且this answer指出,當將數據從Web服務器發送到靜態頁面時,必須使用null的標題。但是下面兩行都沒有工作,所以我該怎麼做?GoLang:將文件頭設置爲空://對於http://請求不起作用

func handler(w http.ResponseWriter, r *http.Request) { 
    w.Header().Add("Access-Control-Allow-Origin", nil) //this line 
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) 
} 

返回錯誤./main.go:42: cannot use nil as type string in argument to w.Header().Add

func handler(w http.ResponseWriter, r *http.Request) { 
    w.Header().Add("Access-Control-Allow-Origin", "") 
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) 
} 

這編譯,但拋出的客戶端錯誤:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/aardvark/posts. (Reason: CORS header 'Access-Control-Allow-Origin' missing)

回答

2

寫了這個問題後,我想嘗試最後一件事出於絕望,和有效。

func handler(w http.ResponseWriter, r *http.Request) { 
    w.Header().Add("Access-Control-Allow-Origin", "null") 
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) 
} 

你應該將字符串設定爲"null",而不是一個空字符串""nil

如果你不認爲這個問題屬於對SO,請留下評論,我會及時把它拿下來。

+0

Kudos! NULL或缺少值的實現在語言和平臺之間是不同的(即JSON's是'null',Python是'None',Go是'nil')。對於HTTP頭文件,這是純文本格式,因此Go中沒有辦法(也可能不需要)將'nil'轉換爲'null'。 – PieOhPah