http - 静态资源的基本认证
问题描述
如何向我的静态资源添加基本身份验证?使用下面的代码,我可以查看标签文件夹中的任何文件。我知道在这个问题中解释了如何做到这一点。http.ResponseWriter
但是,当不使用a 时,我将如何设置标题?
package main
import (
"github.com/gorilla/mux"
"log"
"net/http"
"os"
)
func main() {
port := GetPort()
log.Println("[-] Listening on...", port)
r := mux.NewRouter()
r.PathPrefix("/labels/").Handler(http.StripPrefix("/labels/", http.FileServer(http.Dir("./labels/"))))
err := http.ListenAndServe(port, r)
log.Fatal(err)
}
// GetPort is for herkou deployment
func GetPort() string {
port := os.Getenv("PORT")
if port == "" {
port = "4747"
log.Println("[-] No PORT environment variable detected. Setting to ", port)
}
return ":" + port
}
解决方案
在每个处理程序周围创建一个包装器以传递来自身份验证中间件的请求,该请求将在身份验证完成后进一步转发请求,否则返回错误响应
func authentication(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing authentication")
next.ServeHTTP(w, r)
})
}
// open the dialog to download pdf files.
func dowloadPdf(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", "attachment; filename=YOUR_FILE")
w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
w.Write([]byte("File downloaded"))
}
func main(){
pdfHandler := http.HandlerFunc(dowloadPdf)
http.Handle("/servepdf", authentication(pdfHandler))
http.ListenAndServe(":3000", nil)
}
但是,如果我考虑到在提供静态文件(如 html、css、js 等)时不需要进行身份验证这一事实。最好在验证用户身份后创建一个处理程序来提供 pdf 文件。
您还可以将negorni中间件与 gorilla mux 一起使用,而不是创建自定义中间件。
推荐阅读
- java - 如何在第 n 次出现分隔符之前进行子字符串化?
- php - 使用 .htaccess 从 URL 重写 PHP 变量
- python - python-产生并引发异常
- java - org.springframework.data.mapping.model.MappingInstantiationException:无法用新的布尔字段实例化对象
- twig - Twig if 语句为假
- python - Python 尝试除了不使用 np.arccos
- regex - 加快正则表达式匹配
- r - dplyr 计数事件,如果它没有发生
- android - Android - PWA 无法在独立模式下与服务工作者一起打开
- vtk - 使用 VTK 格式在单元中心定义数据