duanpa5237 2016-11-16 22:42
浏览 34
已采纳

转到:如何使用中间件模式?

I have a function that executes only with specific conditions (e.g. role == 'Administrator'). Now, I use 'if' statement. But it could be situations when number of conditions is high and 'if' with long definition looks not so esthetic.
Is it available mechanism in Go (or related with Go framework) allows implementation of middleware concept (action filters)?

For example, ASP.NET MVC allows to do this:

[MyFilter]
public ViewResult Index()
{
     // Filter will be applied to this specific action method
}

So, MyFilter() implemented in the separate class allows better code composition and testing.

Update: Revel (web framework for the Go) provides similar functionality with Interceptors (function that is invoked by the framework BEFORE or AFTER an action invocation): https://revel.github.io/manual/interceptors.html

  • 写回答

2条回答 默认 最新

  • dongshao4207 2016-11-17 07:54
    关注

    This sort of thing is typically done with middleware in Go. The easiest is to show by example:

    package main
    
    import (
        "fmt"
        "html"
        "log"
        "net/http"
    )
    
    func main() {
        http.HandleFunc("/", handler)
        http.HandleFunc("/foo", middleware(handler))
    
        log.Fatal(http.ListenAndServe(":8080", nil))
    }
    
    func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    }
    
    func middleware(next http.HandlerFunc) http.HandlerFunc {
        return func(w http.ResponseWriter, r *http.Request) {
            r.URL.Path = "/MODIFIED"
    
            // Run the next handler
            next.ServeHTTP(w, r)
        }
    }
    

    As you can see, a middleware is a function that:

    1. accepts a http.HandlerFunc as an argument;
    2. returns a http.HandlerFunc;
    3. calls the http.handlerFunc passed in.

    With this basic technique you can "chain" as many middlewares as you like:

    http.HandleFunc("/foo", another(middleware(handler)))
    

    There are some variants to this pattern, and most Go frameworks use a slightly different syntax, but the concept is typically the same.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器