douxing7101 2017-11-04 22:36
浏览 34

Golang请求中间件库?

I'm using gorrilla mux for my mux for my routing setup.

Is there any open source library that will provide some sort of request middleware?

router.HandleFunc("/products", GetProducts).Methods("GET")

So currently I have the GetProducts function that will return the products etc.

But this is a REST api that I am building, so I have to handle things like loading the user, verifying the 'api token' for the request etc.

I don't want to do this for each and every method so I was hoping I there was some request middleware when I can do this before/after execution, along with adding things like User, Permissions to the context in each middleware function.

  • 写回答

1条回答 默认 最新

  • dongzha2525 2017-11-05 07:53
    关注

    You can use Go Gin HTTP web framework that supports middlewares as well as you want:

    Using middleware:

    func main() {
    // Creates a router without any middleware by default
    r := gin.New()
    
    // Global middleware
    // Logger middleware will write the logs to gin.DefaultWriter even you set with GIN_MODE=release.
    // By default gin.DefaultWriter = os.Stdout
    r.Use(gin.Logger())
    
    // Recovery middleware recovers from any panics and writes a 500 if there was one.
    r.Use(gin.Recovery())
    
    // Per route middleware, you can add as many as you desire.
    r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
    
    // Authorization group
    // authorized := r.Group("/", AuthRequired())
    // exactly the same as:
    authorized := r.Group("/")
    // per group middleware! in this case we use the custom created
    // AuthRequired() middleware just in the "authorized" group.
    authorized.Use(AuthRequired())
    {
        authorized.POST("/login", loginEndpoint)
        authorized.POST("/submit", submitEndpoint)
        authorized.POST("/read", readEndpoint)
    
        // nested group
        testing := authorized.Group("testing")
        testing.GET("/analytics", analyticsEndpoint)
    }
    
    // Listen and serve on 0.0.0.0:8080
    r.Run(":8080")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100