go-http-auth를 사용하여 http.FileServer에서 기본 인증을 수행 할 수 없습니다.Golang : 기본 인증을 사용하여 정적 파일을 제공하는 방법
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))
작동하지만 auth.JustCheck와 함께 사용할 수 없습니다. handleFileServer 함수로 시도했지만 아무 것도 표시되지 않습니다. 트릭이 뭐야?
감사합니다,
는 당신이 시도 않았다'http.HandleFunc ("/ 정적 /", auth.JustCheck (인증, HTTP .StripPrefix (http.FileServer (http.Dir ("static"))) ServeHTTP)? – OneOfOne