Golang请求中间件库?

时间:2017-11-04 22:36:37

标签: go

我使用gorrilla mux作为我的多路复用器进行路由设置。

是否有任何开源库可以提供某种请求中间件?

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

所以目前我有GetProducts函数将返回产品等。

但这是我正在构建的REST API,因此我必须处理诸如加载用户,验证' api令牌等问题。对于请求等。

我不想为每个方法执行此操作,所以我希望我能在执行之前/之后执行此操作时添加一些请求中间件,同时添加User之类的内容,{ {1}}到每个中间件函数的上下文。

1 个答案:

答案 0 :(得分:0)

您可以使用Go Gin支持中间件的HTTP Web框架:

使用中间件:

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