doulvyi2172 2017-11-07 06:11
浏览 201
已采纳

httprouter传递了许多中间件功能

I'm coming from node express, and I was able to pass in as many middleware as possible, for example: routes.use('/*', ensureAuth, logImportant, ... n);

How can I do something similar when using r.GET("/", HomeIndex)?

Am I forced to do something like EnsureAuth(HomeIndex)? Because I can get that to work. Unfortunately, I'm not sure what would be a good way to add as many middlewares as I want without chaining functions together.

Is there a more elegant way so I could somehow use variadic type function to do r.GET("/", applyMiddleware(HomeIndex, m1, m2, m3, m4)? I'm trying that out right now, but I feel like there's a better way to do this.

I've looked at the httprouter issues page, can't find anything :(

Thanks!

  • 写回答

1条回答 默认 最新

  • dongyou5068 2017-11-07 07:20
    关注

    Here is an example how I did it:

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

    Link to code (you can't run it from play.golang.org though): https://play.golang.org/p/BOCt97xcoY

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?