2014-08-28 12 views
5

Ich kann nicht grundlegende Authentifizierung mit http.FileServer verwenden go-http-Auth.Golang: Wie statische Dateien mit Basisauthentifizierung geliefert werden

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) 
} 

Der Code

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

Werke in main() ohne Authentifizierung, aber kann es nicht zusammen mit auth.JustCheck verwenden. Ich habe versucht mit der Funktion handleFileServer, aber nichts wird angezeigt. Was ist der Trick?

Danke, JGR

+1

haben Sie versucht, 'http.HandleFunc ("/ static /", auth.JustCheck (Authenticator, http .StripPrefix (http.FileServer (http.Dir ("statisch"))) ServeHTTP) '? – OneOfOne

Antwort

7

Sie benötigen StripPrefix die ServeHTTP Methode zurückzukehren, zum Beispiel:

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

Vielen Dank, speziell für die Verbesserung Ihres Kommentars zu einem funktionierenden Code.Ich sollte jetzt einen Weg finden, um die Notwendigkeit zu entfernen, zu schreiben zweimal das "statische" URL-Präfix. – jgran

+0

Aber noch, wie man Zugang zu den Argumenten hat (w http.ResponseWriter, r * http.Request) wie in der Funktion doRoot? Ich bin fest damit. – jgran

+0

Ich werde das Beispiel aktualisieren. – OneOfOne