由于静态文件服务器对对所有请求都是透明的,我想把一部分重要文件对部分特权用户开放下载。即下载前,先验证用户权限,权限满足再开放下载(同时隐藏‘真实’地址)
普通用法
添加路由后,直接使用ServeFile方法即可
http.HandleFunc("/static2/", func(w http.ResponseWriter, r *http.Request) {
//your code to check privilege
//if passed, output file
http.ServeFile(w, r, your_file_url)
})
在beego框架下的用法
beego静态文件的介绍参看:https://beego.me/docs/mvc/view/static.md
由于
beego.SetStaticPath("/static","public")
是全局设置,对所有请求透明,需要稍作修改。跟踪了一下代码,Controller的Ctx保存了ResponseWriter, Request参数,demo如下
1,路由设置
beego.Router("/user/testfile",&controllers.UserController{},"*:TestFile")
2,控制器方法
func (c *UserController) TestFile() {
//todo check file if exist
//output file
http.ServeFile(c.Ctx.ResponseWriter, c.Ctx.Request, "private/sample.zip")
}
以上代码的作用是:供用户下载private/sample.zip
用户看到的下载地址是:http://localhost:8080/user/testfile
而实际的下载地址是:http://localhost:8080/private/sample.zip
于是这样就达到隐藏文件的目的。