2014-08-28 3 views
5

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 함수로 시도했지만 아무 것도 표시되지 않습니다. 트릭이 뭐야?

감사합니다,

+1

는 당신이 시도 않았다'http.HandleFunc ("/ 정적 /", auth.JustCheck (인증, HTTP .StripPrefix (http.FileServer (http.Dir ("static"))) ServeHTTP)? – OneOfOne

답변

7

당신은 예를 들어, StripPrefix의 ServeHTTP 방법을 반환해야 JGR :

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

작업 코드에 주석을 적용 해 주셔서 감사합니다. 두 번 "정적"URL 접두어. – jgran

+0

하지만 여전히 doRoot 함수에서와 같이 인수 (w http.ResponseWriter, r * http.Request)에 액세스하는 방법은 무엇입니까? 그걸로 붙어. – jgran

+0

예를 업데이트합니다. – OneOfOne

관련 문제