Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get response result(body) in global Interceptor. #1332

Closed
Thonpson2019 opened this issue Aug 8, 2019 · 1 comment

Comments

@Thonpson2019
Copy link

commented Aug 8, 2019

I want to record operation log in global Interceptor.

app.Get("/save", func(ctx iris.Context) {
	// save data...
	ctx.WriteString("success")
})

app.WrapRouter(func(w http.ResponseWriter, r *http.Request, router http.HandlerFunc) {
	router(w, r)
	path := r.URL.Path
	ctx := app.ContextPool.Acquire(w, r)
	responseResult := ? // ctx.Record() then ctx.Recorder().Body() not work
	if path == "/save" {
		if responseResult == "success" {
			recordOperatingLog(responseResult, ctx)
		}
	}
})
@kataras

This comment has been minimized.

Copy link
Owner

commented Aug 9, 2019

Hello @Thonpson2019,

This doesn't work because you call ctx.Record after the body sent.

  • The ctx.Record must called before response write in order to start recording

Why you need to use the app.WrapRouter for that and not app.Done/DoneGlobal instead ?

Example

package main

import "github.com/kataras/iris"

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

        // start record.
	app.Use(func(ctx iris.Context) {
		ctx.Record()
		ctx.Next()
	})

        // collect and "log".
	app.Done(func(ctx iris.Context) {
		body := ctx.Recorder().Body()

		// Should print success.
		app.Logger().Infof("sent: %s", string(body))
	})
}

And your routes...

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

Or to remove the need of ctx.Next in your main handlers by setting execution rules:

        // It applies per Party and its children,
        // therefore, you can create a routes := app.Party("/path")
        // and set middlewares, their rules and the routes there as well.
	app.SetExecutionRules(iris.ExecutionRules{ 
		Done: iris.ExecutionOptions{Force: true},
	})

	// [Your routes...]
	app.Get("/save", func(ctx iris.Context) {
		ctx.WriteString("success")
	})

1332


Hope that helped, and if so, please give us a star!

@kataras kataras added the question label Aug 9, 2019

@kataras kataras closed this Aug 14, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.