登录
首页 >  Golang >  Go问答

静态资源的基本身份验证

来源:stackoverflow

时间:2024-04-07 08:51:28 244浏览 收藏

本篇文章给大家分享《静态资源的基本身份验证》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

如何向我的静态资源添加基本身份验证?使用下面的代码,我可以查看标签文件夹中的任何文件。我知道在这个问题中已经解释了如何做到这一点。但是,当不使用 http.responsewriter 时,我将如何设置标头?

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

以上就是《静态资源的基本身份验证》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>