大猩猩多媒体定制中间件 [英] Gorilla mux custom middleware
问题描述
例如
包主
进口(
fmt
github.com/gorilla/mux
记录
净/ http
strconv
)
func HomeHandler(response http.ResponseWriter,request * http.Request){
fmt.Fprintf(response,Hello home)
}
func main(){
port:= 3000
portstring:= strconv.Itoa(port)
r:= mux.NewRouter( )
r.HandleFunc(/,HomeHandler)
http.Handle(/,r)
log.Print(Listening on port+ portstring + ...)
err:= http.ListenAndServe(:+ portstring,nil)
if err!= nil {
log.Fatal(ListenAndServe error:,err)
}
}
每个传入请求都应该通过中间件。我如何在这里集成一个midleware?
更新
我会用它结合大猩猩/会话,他们说:
重要说明:如果您不使用大猩猩/多路复用器,则需要将你的
处理程序与context.ClearHandler,否则你会泄漏内存!
简单的方法是在调用
http.ListenAndServe时打包顶层mux: b $ b
如何防止这种情况发生?
只要创建一个包装器,它在Go中相当简单:
func HomeHandler(response http.ResponseWriter,request * http.Request){
fmt.Fprintf(response,Hello home )
}
func中间件(h http.Handler)http.Handler {
返回http.HandlerFunc(func(w http.ResponseWriter,r * http.Request){
log.Println(middleware,r.URL)
h.ServeHTTP(w,r)
})
}
func main(){
r $ = $ m $ $ b $ H
r.HandleFunc(/,HomeHandler)
http.Handle(/,中间件(r))
}
I am using gorilla mux for manage routing. What I am missing is to integrate a middleware between every request.
For example
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"strconv"
)
func HomeHandler(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "Hello home")
}
func main() {
port := 3000
portstring := strconv.Itoa(port)
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
http.Handle("/", r)
log.Print("Listening on port " + portstring + " ... ")
err := http.ListenAndServe(":"+portstring, nil)
if err != nil {
log.Fatal("ListenAndServe error: ", err)
}
}
Every incoming request should pass through the middleware. How can I integrate here a midleware?
Update
I will use it in combination with gorilla/sessions, and they say:
Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory! An easy way to do this is to wrap the top-level mux when calling http.ListenAndServe:
How can I prevent this scenario?
Just create a wrapper, it's rather easy in Go:
func HomeHandler(response http.ResponseWriter, request *http.Request) {
fmt.Fprintf(response, "Hello home")
}
func Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("middleware", r.URL)
h.ServeHTTP(w, r)
})
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
http.Handle("/", Middleware(r))
}
这篇关于大猩猩多媒体定制中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!