有没有办法通过Http.Handle或Http.FileServer传入headers?

Is there a way to pass in headers through Http.Handle or Http.FileServer?

我在 Go 中设置了一个非常基本的服务器

fs := http.FileServer(http.Dir("./public"))
 http.Handle("/",fs)

但问题是:我希望人们使用 fetch() 访问我的 URL。这是不可能的,但是由于设置了 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.

我需要找到一种方法来传递 header Access-Control-Allow-Origin:*,但我不知道如何使用 http.Handlehttp.FileServer,只有 http.HandleFunc.

我不能使用 http.HandleFunc,因为据我所知,它不允许我提供文件服务,而且我不想自己使用文件处理系统获取文件(我可能不得不除非有其他方法,否则将此作为最后的手段)。另外,它效率低下。为什么要重新发明轮子,尤其是当那个轮子比我想出的要好得多时?

是否有任何方式无论如何http.Handle()发送header?

我是 Go 的新手,有一段时间没有使用静态类型的语言,也没有使用处理传入 URL 的语言(我主要使用 PHP,所以...),所以我可能会或可能不会很好地掌握这个概念。

您可以将 http.FileServer 包裹在 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)
    }
}

然后将其用于:

fs := http.FileServer(http.Dir("./public"))
http.Handle("/", cors(fs))

底层机制是 http.HandlerFunc 实现了 http.Handler 接口。