Skip to content

Instantly share code, notes, and snippets.

@lestrrat
Last active October 25, 2017 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lestrrat/048510e0a7340b3bf682530a79ff6137 to your computer and use it in GitHub Desktop.
Save lestrrat/048510e0a7340b3bf682530a79ff6137 to your computer and use it in GitHub Desktop.
// Wrap the handler with a context that holds the transaction
func withTx(h http.Handler) http.Handler {
return http.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
tx, err := globalDB.BeginTx(r.Context())
if err != nil {
http.Error(...)
return
}
r = r.WithContext(context.WithTx(r.Context(), tx))
h.ServeHTTP(w, r)
})
}
func myHandler(w http.ResponseWriter, r *http.Request) {
tx, err := context.Tx(r.Context())
...
}
// context is declared as an internal package, so it looks almost like the real context
package context
type Context = context.Context
type CancelFunc = context.CancelFunc
func WithCancel(...) {}
func WithTimeout(...) {}
func WithTx(ctx context.Context, tx *sql.Tx) context.Context {
... うまいこと入れる
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment