2014-08-28 1 views
5

Я не могу выполнить базовую работу с аутентификацией с http.FileServer с помощью go-http-auth.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, но ничего не отображается. Какая уловка?

Спасибо, JGR

+1

вы пытались 'http.HandleFunc ("/ статический /", auth.JustCheck (аутентификатор, HTTP .StripPrefix (http.FileServer (http.Dir («статический»))). ServeHTTP) '? – OneOfOne

ответ

7

Вы должны вернуть метод ServeHTTP StripPrefix, например:

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

Но все же, как получить доступ к аргументам (w http.ResponseWriter, r * http.Request), как в функции doRoot? застрял с ним. – jgran

+0

Я обновлю пример. – OneOfOne