go - httprouter传入很多中间件函数

标签 go middleware httprouter

我来自 Node Express,我能够传入尽可能多的中间件,例如:routes.use('/*', EnsureAuth, logImportant, ... n);

使用r.GET("/", HomeIndex)时如何做类似的事情?

我是否被迫做类似 EnsureAuth(HomeIndex) 的事情?因为我可以让它发挥作用。不幸的是,我不确定在不将函数链接在一起的情况下添加尽可能多的中间件的好方法是什么。

是否有一种更优雅的方法,以便我可以以某种方式使用可变参数类型函数来执行 r.GET("/", applyMiddleware(HomeIndex, m1, m2, m3, m4)?现在正在尝试,但我觉得有更好的方法来做到这一点。

我查看了 httprouter 问题页面,找不到任何内容:(

谢谢!

最佳答案

以下是我的操作示例:

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"

    "github.com/julienschmidt/httprouter"
    "github.com/justinas/alice"
)

// m1 is middleware 1
func m1(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        //do something with m1
        log.Println("m1 start here")
        next.ServeHTTP(w, r)
        log.Println("m1 end here")
    })
}

// m2 is middleware 2
func m2(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        //do something with m2
        log.Println("m2 start here")
        next.ServeHTTP(w, r)
        log.Println("m2 end here")
    })
}

func index(w http.ResponseWriter, r *http.Request) {
    // get httprouter.Params from request context
    ps := r.Context().Value("params").(httprouter.Params)
    fmt.Fprintf(w, "Hello, %s", ps.ByName("name"))
}

// wrapper wraps http.Handler and returns httprouter.Handle
func wrapper(next http.Handler) httprouter.Handle {
    return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
        //pass httprouter.Params to request context
        ctx := context.WithValue(r.Context(), "params", ps)
        //call next middleware with new context
        next.ServeHTTP(w, r.WithContext(ctx))
    }
}

func main() {
    router := httprouter.New()

    chain := alice.New(m1, m2)

    //need to wrap http.Handler to be compatible with httprouter.Handle
    router.GET("/user/:name", wrapper(chain.ThenFunc(index)))

    log.Fatal(http.ListenAndServe(":9000", router))
}

链接到代码(但您无法从 play.golang.org 运行它):https://play.golang.org/p/BOCt97xcoY

关于go - httprouter传入很多中间件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47151085/

相关文章:

http - 您可以修改传出 HTTP 请求的正文吗?

node.js - Express - 如何修改请求然后重定向到另一条路线?

go - 在 rest api 中使用 goroutine - 出现未定义的错误

go - 端点 Google ID JWT 和 Golang oauth2 : have id_token, 需要 access_token?

go - golang 数学/大库中的奇怪语法

go - 为什么当我超时函数时不调用延迟?

struct - 去深/浅复制

middleware - 通过中间件执行查询