一个响应记录器是 Iris 特定的 http.ResponseWriter,它记录了发送的响应体,状态码和响应头,你可以在任何这个路由的请求处理器链上的处理器内部操作它。

  • 在发送数据前调用 Context.Record
  • Context.Recorder() 返回一个 ResponseRecorder。它的方法可以用来操作和找回响应。

ResponseRecorder 类型包含了标准的 Iris ResponseWriter 方法和下列的方法。

Body 返回目前为止 Writer 写入的响应体数据。不要使用它来编辑响应体。

  1. Body() []byte

使用这个来清除响应体

  1. ResetBody()

使用 Write/Writef/WriteString 流式写入,SetBody/SetBodyString 设置响应体。

  1. Write(contents []byte) (int, error)
  2. Writef(format string, a ...interface{}) (n int, err error)
  3. WriteString(s string) (n int, err error)
  4. SetBody(b []byte)
  5. SetBodyString(s string)

在调用 Context.Record之前,使用 ResetHeaders 重置响应头为原始状态。

  1. ResetHeaders()

清除所有的头部信息。

  1. ClearHeaders()

同时重置响应体,响应头和状态码。

  1. Reset()

示例(Example)

在一个全局拦截器中记录操作日志。

  1. package main
  2. import "github.com/kataras/iris/v12"
  3. func main() {
  4. app := iris.New()
  5. // start record.
  6. app.Use(func(ctx iris.Context) {
  7. ctx.Record()
  8. ctx.Next()
  9. })
  10. // collect and "log".
  11. app.Done(func(ctx iris.Context) {
  12. body := ctx.Recorder().Body()
  13. // Should print success.
  14. app.Logger().Infof("sent: %s", string(body))
  15. })
  16. }

注册路由:

  1. app.Get("/save", func(ctx iris.Context) {
  2. ctx.WriteString("success")
  3. ctx.Next() // calls the Done middleware(s).
  4. })

或者为了消除你的主处理器中对 ctx.Next 的需求,改变 Iris 处理器的执行规则,你可以如下所示:

  1. // It applies per Party and its children,
  2. // therefore, you can create a routes := app.Party("/path")
  3. // and set middlewares, their rules and the routes there as well.
  4. app.SetExecutionRules(iris.ExecutionRules{
  5. Done: iris.ExecutionOptions{Force: true},
  6. })
  7. // [The routes...]
  8. app.Get("/save", func(ctx iris.Context) {
  9. ctx.WriteString("success")
  10. })