GoLang:将 file:// 到 http:// 请求的 header 设置为 null 无效

GoLang: Setting header to null for a file:// to http:// request not working

This answer about static to static (file:// -> file://) states that a webserver (http://) can be used to serve files to a local static page (file://) without violating CORS. And this answer 指出当从网络服务器向静态页面发送数据时,必须使用 null 的 header。但是下面两行都不起作用,那我该怎么做呢?

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:])
}

returns错误./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)

写完这个问题后,我绝望地想尝试最后一件事,结果成功了。

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,欢迎留言,我会及时撤下。