Skip to content

Commit 2107429

Browse files
committed
update context key
1 parent c9157c8 commit 2107429

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

mux.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,17 @@ var ErrGroupExisted = errors.New("Group Existed")
3030
// ErrParamsKeyEmpty is the error returned by HandleFunc when the params key is empty.
3131
var ErrParamsKeyEmpty = errors.New("Params key must be not empty")
3232

33-
// ContextKey represents the context key.
34-
type ContextKey string
33+
// contextKey is a key for use with context.WithValue. It's used as
34+
// a pointer so it fits in an interface{} without allocation.
35+
type contextKey struct {
36+
name string
37+
}
38+
39+
// String returns a context key.
40+
func (k *contextKey) String() string { return "github.com/hslam/rum context key " + k.name }
3541

36-
// ContextKeyRecovery is the context key of recovery.
37-
const ContextKeyRecovery = ContextKey("mux:context:recovery")
42+
// RecoveryContextKey is a context key.
43+
var RecoveryContextKey = &contextKey{"recovery"}
3844

3945
// Mux is an HTTP request multiplexer.
4046
type Mux struct {
@@ -144,7 +150,7 @@ func (m *Mux) serveEntry(entry *Entry, w http.ResponseWriter, r *http.Request) {
144150

145151
// Recovery returns a recovery handler function that recovers from any panics and writes a 500 status code.
146152
func Recovery(w http.ResponseWriter, r *http.Request) {
147-
err := r.Context().Value(ContextKeyRecovery)
153+
err := r.Context().Value(RecoveryContextKey)
148154
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
149155
w.Header().Set("X-Content-Type-Options", "nosniff")
150156
w.WriteHeader(http.StatusInternalServerError)
@@ -155,7 +161,7 @@ func (m *Mux) serveHandler(handler http.Handler, w http.ResponseWriter, r *http.
155161
if m.recovery != nil {
156162
defer func() {
157163
if err := recover(); err != nil {
158-
ctx := context.WithValue(r.Context(), ContextKeyRecovery, err)
164+
ctx := context.WithValue(r.Context(), RecoveryContextKey, err)
159165
m.recovery.ServeHTTP(w, r.WithContext(ctx))
160166
}
161167
}()

mux_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ import (
1111
"testing"
1212
)
1313

14+
func TestContextKey(t *testing.T) {
15+
if RecoveryContextKey.String() != fmt.Sprint(RecoveryContextKey) {
16+
t.Error()
17+
}
18+
}
19+
1420
func TestParseMatch(t *testing.T) {
1521
pattern := "/db/:key/meng/:value/huang"
1622
i := strings.Index(pattern, ":")

0 commit comments

Comments
 (0)