我在 Go 中设置了一个非常基本的服务器
fs := http.FileServer(http.Dir("./public"))
http.Handle("/",fs)
Run Code Online (Sandbox Code Playgroud)
但问题是:我希望人们使用fetch()
. 然而,由于设置了 CORS,这是不可能的。
Access to fetch 'xxxxx' from origin 'null' has
been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch
the resource with CORS disabled.
Run Code Online (Sandbox Code Playgroud)
我需要找到一种方法来传入标头Access-Control-Allow-Origin:*
,但我不知道如何使用http.Handle
or http.FileServer
, only http.HandleFunc
。
我无法使用,http.HandleFunc
因为据我所知,它不允许我提供文件,而且我宁愿不使用文件处理系统自己获取文件(我可能必须将其作为最后的手段,除非有另一个方法)方式)。另外,它的效率很低。为什么要重新发明轮子,尤其是当这个轮子比我能想出的更好的时候?
有什么方法可以发送标头吗http.Handle()
?
我对 Go 还很陌生,我已经有一段时间没有做过静态类型语言了,也没有做过处理传入 URL 的语言(我主要使用 PHP,所以......),所以我可能有也可能没有一个好的对概念的把握。
您可以将 a 包裹http.FileServer
在 a 中http.HandleFunc
:
func cors(fs http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// do your cors stuff
// return if you do not want the FileServer handle a specific request
fs.ServeHTTP(w, r)
}
}
Run Code Online (Sandbox Code Playgroud)
然后将其与以下命令一起使用:
fs := http.FileServer(http.Dir("./public"))
http.Handle("/", cors(fs))
Run Code Online (Sandbox Code Playgroud)
底层机制是http.HandlerFunc
实现http.Handler
接口。