2014-08-28 33 views
5

http.FileServer ile go-http-auth kullanarak temel kimlik doğrulaması yapamıyorum.Golang: Temel kimlik doğrulamasıyla statik dosyalar nasıl sunulur

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

kod doğrulaması olmadan ana() içinde

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

çalışır, ancak auth.JustCheck birlikte kullanamazsınız. HandleFileServer işleviyle denedim, ancak hiçbir şey görüntülenmiyor. Hilesi ne?

sayesinde

+1

sen denedin mi 'http.HandleFunc ("/ static /" auth.JustCheck (doğrulayıcı http .StripPrefix (http.FileServer (http.Dir ("statik"))). ServeHTTP) '? – OneOfOne

cevap

7

Örneğin, StripPrefix en ServeHTTP yöntemini dönmek gerekir 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

Yorumunuzu özellikle çalışma koduna göre düzeltmek için çok teşekkürler. Yazma gereğini ortadan kaldırmanın bir yolunu bulmalıyım. "Statik" url önekinin iki katı – jgran

+0

Ama yine de, argümanlara erişim (w http.ResponseWriter, r * http.Request) doRoot işlevinde nasıl? onunla sıkışmış. – jgran

+0

Örneği güncelleyeceğim. – OneOfOne

İlgili konular