go - fasthttp + fasthttprouter,尝试写中间件

标签 go middleware fasthttp

我目前正在尝试编写一些中间件来使用 fasthttp 和 fasthttprouter。我被卡住了。

func jwt(h fasthttprouter.Handle) fasthttprouter.Handle {
myfunc := func(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) {
    fmt.Println(string(ctx.Request.Header.Cookie("Authorization")))
}

return myfunc
}

我现在如何运行实际的处理程序?我觉得我错过了一些非常简单的东西。

我已通读这篇博文:Middleware in Golang .但是我迷路了。

有什么想法吗?

问候

最佳答案

例如,让我们创建一个中间件函数来处理 CORS,使用:

github.com/buaazp/fasthttprouter github.com/valyala/fasthttp

var (
    corsAllowHeaders     = "authorization"
    corsAllowMethods     = "HEAD,GET,POST,PUT,DELETE,OPTIONS"
    corsAllowOrigin      = "*"
    corsAllowCredentials = "true"
)

func CORS(next fasthttp.RequestHandler) fasthttp.RequestHandler {
    return func(ctx *fasthttp.RequestCtx) {

        ctx.Response.Header.Set("Access-Control-Allow-Credentials", corsAllowCredentials)
        ctx.Response.Header.Set("Access-Control-Allow-Headers", corsAllowHeaders)
        ctx.Response.Header.Set("Access-Control-Allow-Methods", corsAllowMethods)
        ctx.Response.Header.Set("Access-Control-Allow-Origin", corsAllowOrigin)

        next(ctx)
    }
}

现在我们将这个中间件函数链接到我们的索引处理程序上,并将其注册到路由器上。

func Index(ctx *fasthttp.RequestCtx) {
    fmt.Fprint(ctx, "some-api")
}

func main() {
    router := fasthttprouter.New()
    router.GET("/", Index)

    if err := fasthttp.ListenAndServe(":8181", CORS(router.Handler)); err != nil {
        log.Fatalf("Error in ListenAndServe: %s", err)
    }
}

关于go - fasthttp + fasthttprouter,尝试写中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38557843/

相关文章:

go - filepath.Walk() 返回 0xc08402f180

go - 复合词的文件名约定?

go - 如何从Golang的*fasthttp.Request中获取头部内容?

golang将fasthttp替换为gin, slice 边界超出范围运行时错误

docker - 在 Docker 容器中部署 Golang 应用程序

struct - 星号(* struct)符号在golang中是什么意思

node.js - 如何将变量从 Connect 的中间件传递到 app.get-action?

angularjs - Passport 和 Angular 之间的中间件

routes - Slim3 从 CSRF 中间件中排除路由