大猩猩多媒体定制中间件 [英] Gorilla mux custom middleware

查看:119
本文介绍了大猩猩多媒体定制中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gorilla mux进行管理路由。我所缺少的是在每个请求之间集成一个中间件。



例如

 包主

进口(
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆