首页 > 解决方案 > 静态资源的基本认证

问题描述

如何向我的静态资源添加基本身份验证?使用下面的代码,我可以查看标签文件夹中的任何文件。我知道在这个问题中解释了如何做到这一点。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
}

标签: httpauthenticationgobasic-authenticationgorilla

解决方案


在每个处理程序周围创建一个包装器以传递来自身份验证中间件的请求,该请求将在身份验证完成后进一步转发请求,否则返回错误响应

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 一起使用,而不是创建自定义中间件。


推荐阅读