donglang6656 2018-06-14 18:43
浏览 78

Gorilla Mux,静态文件服务器的中间件

Please see my code below. As you can see it's a simple service with two endpoints:

  1. /test <-- basic auth protected using middleware
  2. /static <-- serves all the files in the ./static directory

Now I'm trying to add the basic authentication middleware pattern to the /static endpoint as well, but for some reason I can't figure out how. I'm having trouble converting the *route (the outcome of r.PathPrefix) to something the middleware() function understands. (I've also created a playground, but due to the external import, this won't work)

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)
    }
}
  • 写回答

1条回答 默认 最新

  • doubang9906 2018-06-14 19:59
    关注

    Well, turns out I used an ancient version of mux, which was lacking the use() function :).

    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致