转到:如何使用中间件模式? [英] Go: How to use middleware pattern?

查看:98
本文介绍了转到:如何使用中间件模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个仅在特定条件下才能执行的功能(例如 role ==‘Administrator’)。现在,我使用'if'语句。但是可能是条件数量很高并且长定义的'if'看起来不太美观的情况。

它在Go中是否可用(或与Go框架有关)允许实现中间件概念(动作过滤器)?


例如,ASP.NET MVC允许这样做:

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
}

因此,在单独的类中实现的MyFilter()允许更好的代码组成和测试。

更新:
Revel(Go的网络框架)提供了与
拦截器类似的功能(在动作调用之前或之后由框架调用的功能): https://revel.github.io/manual/interceptors.html

推荐答案

这类事情通常是通过Go中的中间件完成的。最简单的例子是:

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. 接受 http.HandlerFunc 作为参数;

  2. 返回 http.HandlerFunc ;

  3. 调用s传入的 http.handlerFunc

  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)))






此模式有一些变体,并且大多数Go框架使用的语法略有不同,但概念通常相同。


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

这篇关于转到:如何使用中间件模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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