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 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端