duanmanmian7589 2014-08-28 15:02
浏览 82
已采纳

如何使用基本身份验证提供静态文件?

I cannot make basic authentication work with http.FileServer using github.com/abbot/go-http-auth.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/abbot/go-http-auth"
)

func Secret(user, realm string) string {
    users := map[string]string{
        "john": "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1", //hello
    }

    if a, ok := users[user]; ok {
        return a
    }
    return ""
}

func doRoot(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "<h1>static file server</h1><p><a href='./static'>folder</p>")
}

func handleFileServer(w http.ResponseWriter, r *http.Request) {
    fs := http.FileServer(http.Dir("static"))
    http.StripPrefix("/static/", fs)
}

func main() {

    authenticator := auth.NewBasicAuthenticator("localhost", Secret)

    // how to secure the FileServer with basic authentication??
    // fs := http.FileServer(http.Dir("static"))
    // http.Handle("/static/", http.StripPrefix("/static/", fs))

    http.HandleFunc("/static/", auth.JustCheck(authenticator, handleFileServer))

    http.HandleFunc("/", auth.JustCheck(authenticator, doRoot))

    log.Println(`Listening... http://localhost:3000
 folder is ./static
 authentication in map users`)
    http.ListenAndServe(":3001", nil)
}

The code:

fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

works in main() without authentication, but cannot use it along with auth.JustCheck. I tried with handleFileServer function, but nothing is displayed. What's the trick?

  • 写回答

1条回答 默认 最新

  • douou5933 2014-08-28 17:36
    关注

    You need to return StripPrefix's ServeHTTP method, for example:

    func handleFileServer(dir, prefix string) http.HandlerFunc {
        fs := http.FileServer(http.Dir(dir))
        realHandler := http.StripPrefix(prefix, fs).ServeHTTP
        return func(w http.ResponseWriter, req *http.Request) {
            log.Println(req.URL)
            realHandler(w, req)
        }
    }
    
    func main()
        //....
        http.HandleFunc("/static/", auth.JustCheck(authenticator, handleFileServer("/tmp", "/static/")))
        //....
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料