Khi chúng ta nói về Middleware trong Iris, chúng ta đang nói về việc chạy mã trước và / hoặc sau mã xử lý chính của chúng ta trong vòng đời yêu cầu HTTP. Ví dụ, phần mềm trung gian ghi nhật ký có thể ghi chi tiết yêu cầu vào nhật ký,  sau đó gọi mã xử lý, trước khi viết chi tiết về phản hồi cho nhật ký. Một trong những điều thú vị về phần mềm trung gian là các đơn vị này cực kỳ linh hoạt và có thể tái sử dụng.

Phần mềm trung gian chỉ là một dạng Handler của func(ctx iris.Context), phần mềm trung gian đang được thực thi khi phần mềm trung gian trước đó gọi ctx.Next(), điều này có thể được sử dụng để xác thực, tức là nếu yêu cầu được xác thực thì hãy gọi ctx.Next() để xử lý với phần còn lại của chuỗi trình xử lý trong yêu cầu nếu không thì phản hồi lỗi.

 


package main

import "github.com/kataras/iris/v12"

func main() {
    app := iris.New()
    // or app.Use(before) and app.Done(after).
    app.Get("/", before, mainHandler, after)
    app.Run(iris.Addr(":8080"))
}

func before(ctx iris.Context) {
    shareInformation := "this is a sharable information between handlers"

    requestPath := ctx.Path()
    println("Before the mainHandler: " + requestPath)

    ctx.Values().Set("info", shareInformation)
    ctx.Next() // execute the next handler, in this case the main one.
}

func after(ctx iris.Context) {
    println("After the mainHandler")
}

func mainHandler(ctx iris.Context) {
    println("Inside mainHandler")

    // take the info from the "before" handler.
    info := ctx.Values().GetString("info")

    // write something to the client as a response.
    ctx.HTML("<h1>Response</h1>")
    ctx.HTML("<br/> Info: " + info)

    ctx.Next() // execute the "after".
}
$ go run main.go # and navigate to the http://localhost:8080
Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.
Before the mainHandler: /
Inside mainHandler
After the mainHandler

Globally

package main

import "github.com/kataras/iris/v12"

func main() {
    app := iris.New()

    // register our routes.
    app.Get("/", indexHandler)
    app.Get("/contact", contactHandler)

    // Order of those calls does not matter,
    // `UseGlobal` and `DoneGlobal` are applied to existing routes
    // and future routes also.
    //
    // Remember: the `Use` and `Done` are applied to the current party's and its children,
    // so if we used the `app.Use/Done before the routes registration
    // it would work like UseGlobal/DoneGlobal in this case,
    // because the `app` is the root "Party".
    app.UseGlobal(before)
    app.DoneGlobal(after)

    app.Run(iris.Addr(":8080"))
}

func before(ctx iris.Context) {
     // [...]
}

func after(ctx iris.Context) {
    // [...]
}

func indexHandler(ctx iris.Context) {
    // write something to the client as a response.
    ctx.HTML("<h1>Index</h1>")

    ctx.Next() // execute the "after" handler registered via `Done`.
}

func contactHandler(ctx iris.Context) {
    // write something to the client as a response.
    ctx.HTML("<h1>Contact</h1>")

    ctx.Next() // execute the "after" handler registered via `Done`.
}

Bạn cũng có thể sử dụng ExecutionRules để buộc các trình xử lý Done được thực thi mà không cần ctx.Next() trong các trình xử lý tuyến của bạn, hãy làm như sau:

app.SetExecutionRules(iris.ExecutionRules{
    // Begin: ...
    // Main:  ...
    Done: iris.ExecutionOptions{Force: true},
})

 


Chuyển đổi http.Handler/HandlerFunc

Tuy nhiên bạn không bị giới hạn đối với họ - bạn có thể tự do sử dụng bất kỳ phần mềm trung gian của bên thứ ba nào tương thích với gói net/http.

Iris không giống với những thứ khác, tương thích 100% với các tiêu chuẩn và đó là lý do tại sao phần lớn các công ty lớn thích ứng với quy trình làm việc của họ, như mạng lưới truyền hình Hoa Kỳ rất nổi tiếng, nó được cập nhật và nó sẽ luôn được liên kết với gói net/http được các tác giả Go hiện đại hóa trên mỗi bản phát hành mới của ngôn ngữ lập trình Go.

Bất kỳ phần mềm trung gian của bên thứ ba nào được viết cho net/http đều tương thích với Iris bằng iris.FromStd(aThirdPartyMiddleware). Hãy nhớ rằng ctx.ResponseWriter() and ctx.Request() trả về cùng một đối số đầu vào  net/http của một http.Handler.

Dưới đây là danh sách một số trình xử lý được tạo riêng cho Iris:

 


Built-in 

MiddlewareExample
basic authenticationiris/_examples/authentication/basicauth
localization and internationalizationiris/_examples/miscellaneous/i81n
request loggeriris/_examples/http_request/request-logger
HTTP method override

iris/middleware/methodoverride/methodoverride_test.go

profiling (pprof)iris/_examples/miscellaneous/pprof
Google reCAPTCHA

 

iris/_examples/miscellaneous/recaptcha

  

 


Community made

Hầu hết các trình xử lý thử nghiệm được chuyển sang hoạt động với hình thức xử lý cảu iris, từ các nguồn của bên thứ ba.

Middleware

Description

Example

jwtMiddleware checks for a JWT on the Authorization header on incoming requests and decodes it.iris-contrib/middleware/jwt/_example
corsHTTP Access Control.iris-contrib/middleware/cors/_example
secure

Middleware that implements a few quick security wins.

iris-contrib/middleware/secure/_example
tollboothGeneric middleware to rate-limit HTTP requests.iris-contrib/middleware/tollbooth/_examples/limit-handler

cloudwatch

AWS cloudwatch metrics middleware.

iris-contrib/middleware/cloudwatch/_example

new relicOfficial New Relic Go Agent.iris-contrib/middleware/newrelic/_example
prometheusEasily create metrics endpoint for the prometheus instrumentation tooliris-contrib/middleware/prometheus/_example
casbinAn authorization library that supports access control models like ACL, RBAC, ABACiris-contrib/middleware/casbin/_examples
ravenSentry client in Goiris-contrib/middleware/raven/_example
csrfCross-Site Request Forgery Protection

iris-contrib/middleware/csrf/_example

Phần tiếp theo chúng ta sẽ tìm hiểu về Xử lý lỗi HTTP