请参阅下面的代码。正如您所看到的,它是一个带有两个端点的简单服务:
现在我正在尝试将基本身份验证中间件模式添加到/ static端点,但由于某种原因我无法弄清楚如何。我无法将*route
(r.PathPrefix的结果)转换为middleware()
函数理解的内容。 (我还创建了一个playground,但由于外部导入,这不起作用)
package main
import (
"encoding/base64"
"log"
"net/http"
"strings"
"github.com/gorilla/mux"
)
const (
username = "test"
password = "test"
)
func main() {
r := mux.NewRouter()
// add normal endpoint
r.HandleFunc("/test", middleWare(myHandler, basicAuth))
// add static
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:8080",
}
log.Print("listening on 0.0.0.0:8080")
log.Fatal(srv.ListenAndServe())
}
func myHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("yes!"))
return
}
func middleWare(h http.HandlerFunc, middleware ...func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc {
for _, m := range middleware {
h = m(h)
}
return h
}
func basicAuth(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
http.Error(w, "Not authorized", 401)
return
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
http.Error(w, err.Error(), 401)
return
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
http.Error(w, "Not authorized", 401)
return
}
if pair[0] != username || pair[1] != password {
http.Error(w, "Not authorized", 401)
return
}
h.ServeHTTP(w, r)
}
}
答案 0 :(得分:0)
好吧,结果我使用了一个古老版本的mux,它缺少use()
函数:)。