Last active
October 25, 2017 06:52
-
-
Save lestrrat/048510e0a7340b3bf682530a79ff6137 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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