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

时间:2014-08-28 15:02:28

标签: go basic-authentication fileserver

我无法使用go-http-auth。

对http.FileServer进行基本身份验证
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)
}

代码

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

在main()中无需身份验证,但不能与auth.JustCheck一起使用。我尝试使用handleFileServer函数,但没有显示任何内容。这个诀窍是什么?

谢谢, JGR

1 个答案:

答案 0 :(得分:9)

您需要返回StripPrefix的ServeHTTP方法,例如:

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/")))
    //....
}