This is a creation in Article, where the information may have evolved or changed.
Tonight, a simple one, feeling quite concise and practical, can be share out
mux_filter.go
123456789Ten One A - - the - - - + - + A at - - - - - in - to + - the * $Panax Notoginseng - the |
Package utils Import ( "Net/http" "Github.com/gorilla/mux" ) var router *mux. Router type httpfunc func(w http. Responsewriter , r *http. Request ) bool type routefilter struct { Filters []httpfunc hdlrhttp. Handlerfunc } func newroutefilter() *routefilter { return &routefilter{} } func (f *routefilter) addfilter (h httpfunc) *routefilter { F. Filters = Append (F. Filters , h ) return F } func (f *routefilter) Handler(H http. Handlerfunc ) *routefilter { F. HDLR = h return F } func (f *routefilter) servehttp(W http. Responsewriter , req * http . Request ) { for _, hdlr : = range F. Filters { if ! HDLR (w, req) { return } } F. HDLR (w, req) }
|
Use the method (implement a Basic Auth Filter):
utils.go
123456789Ten One A - - the - - - + - + A at - - - - - in - to |
Package Common Import ( "Net/http""Strings") type authfunc func(string, string) BOOL func authfilterwrapper(authfunc authfunc) func (w http. Responsewriter , r *http. Request ) bool { return func(w http. Responsewriter , r *http. Request ) bool { _, ok : = R. Header ["Authorization"] if ! OK { http. Error (w, "need Authorization Header", http. statusbadrequest ) return false } auth : = strings. splitn (R. Header ["Authorization"] [0], " " , 2 ) if len(auth) ! = 2 { http. Error (w, "Bad Syntax", http. ) statusbadrequest ) return false } if ! Authfunc (auth[0], auth[1]) { http. Error (w, "Authorization Failed", http. statusunauthorized ) return false } return true }}
|
app.go
1 2 3 4 5 Span class= "Line-number" >6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
func userauth(method, payload string) BOOL { Switch method { Case "Basic": P, _ : = base64. stdencoding . decodestring (payload) pair : = strings. splitn (string(P), ":", 2) if len(pair) ! = 2 { return false } return true Case "Token": return true } return false } func inithandlers(R *mux. ) Router ) { s : = R. Pathprefix (url_prefix). Subrouter () s. Handle ("/test", utils. Newroutefilter (). addfilter(Common. Authfilterwrapper (userauth)). Handler(testhandler)) } func testhandler(w http. Responsewriter , r *http. Request ) { w. Write ([]byte("OK")) }
|