[2019-09-20 15:12:46 最后更新]
[golang]http.FileServer 中如何控制不让访问目录及添加 "Access-Control-Allow-Origin"
golang 默认的 http 模块可以很简单的搭建一个文件访问服务器,例如这样
http.Handle("/html/", http.FileServer(http.Dir(""))); //只有这样才能正确的访问 http://127.0.0.1:8888/html/mail_vip.html
但这样出来的文件系统有个问题,即是不能跨域的,而且还会暴露整个文件夹下的全部文件。找了好久总觉得应该有什么属性能配置,不过未果。目前能找到的方法基本上都是扩展上面代码中的
http.FileServer 部分,这个函数有么有后会得到一个 fileHandler 。然后再定义一个 http.HandleFunc 来代替前面的 http.Handle ,这样就可以在 http.HandleFunc 函数中做完想做的事情后再
调用 fileHandler.ServeHTTP(w ResponseWriter, r *Request) 就可以了。一旦理解了这个原理,倒也是蛮简单的。
相关源码在 D:\Go\src\net\http\fs.go
示例如下
--------------------------------------------------------
var h = http.FileServer(http.Dir(""));
static_fs = h;
http.HandleFunc("/html/", staticHandler);
//2019 静态文件扩展
//原文链接:https://blog.csdn.net/fyxichen/article/details/60570484
//这里可以自行定义安全策略
var static_fs http.Handler;
//func static(w http.ResponseWriter, r *http.Request) {
func staticHandler(w http.ResponseWriter, r *http.Request) {
defer PrintError("staticHandler");
fmt.Printf("访问静态文件:%s\n", r.URL.Path)
//old := r.URL.Path
//r.URL.Path = strings.Replace(old, "/static", "/client", 1)
//staticfs.ServeHTTP(w, r);
//Ajax跨域问题的两种解决方法之一,据说 html5 后的才支持
w.Header().Set("Access-Control-Allow-Origin", "*");
static_fs.ServeHTTP(w, r);
}//