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

Run code before and after request? #2009

Open
crazyprimes opened this issue Jul 9, 2019 · 1 comment
Open

Run code before and after request? #2009

crazyprimes opened this issue Jul 9, 2019 · 1 comment

Comments

@crazyprimes
Copy link

Problem statement

In frameworks like Flask, you can e.g. start a database transaction before the request starts, and commit/rollback when the request ends. Is there a way to do the same here? I can sort of get the start logic working by making a middleware, but I am not sure how to intercept as a final thing before the response is sent to the user?

Thanks.

@casualjim
Copy link
Member

You can use a middleware to this end.

func beforeAndAfter(db some.DBConn, next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Do something before the request
   next.ServeHTTP(w, r)
    // Do something after the request
  })
}

In your case you may want to use something like httpsnoop to wrap the response writer and add some logic in there that allows you to intercept the content.

@fredbi fredbi added the faq label Oct 19, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants