2014-08-28 14 views
5

Tôi không thể thực hiện xác thực cơ bản với http.FileServer bằng go-http-auth.Golang: Cách phân phát tệp tĩnh với xác thực cơ bản

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

công trình trong main() mà không xác thực, nhưng không thể sử dụng nó cùng với auth.JustCheck. Tôi đã thử với hàm handleFileServer, nhưng không có gì được hiển thị. Bí quyết là gì?

Cảm ơn, JGR

+1

bạn đã thử 'http.HandleFunc ("/ tĩnh /", auth.JustCheck (xác thực, http .StripPrefix (http.FileServer (http.Dir ("tĩnh"))) ServeHTTP) '? – OneOfOne

Trả lời

7

Bạn cần phải trả lại phương pháp ServeHTTP StripPrefix của, ví dụ:

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

Cảm ơn bạn rất nhiều, đặc biệt để tinh chỉnh bình luận của bạn thành một mã làm việc. Bây giờ tôi sẽ tìm cách xóa bỏ nhu cầu viết hai lần tiền tố url "tĩnh" – jgran

+0

Nhưng vẫn còn, làm thế nào để có quyền truy cập vào các đối số (w http.ResponseWriter, r * http.Request) như trong hàm doRoot? mắc kẹt với nó. – jgran

+0

Tôi sẽ cập nhật ví dụ. – OneOfOne

Các vấn đề liên quan