Skip to content

Commit 836be3f

Browse files
committed
Slightly better way to handle useNumber
1 parent 6207357 commit 836be3f

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

parser.go

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke
162162
unmarshal = json.Unmarshal
163163
}
164164

165+
// JSON Unmarshal the header
165166
err = unmarshal(headerBytes, &token.Header)
166167
if err != nil {
167168
return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err)
@@ -175,25 +176,23 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke
175176
return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err)
176177
}
177178

178-
// If `useJSONNumber` is enabled then we must use *json.Decoder to decode
179+
// If `useJSONNumber` is enabled, then we must use *json.Decoder to decode
179180
// the claims. However, this comes with a performance penalty so only use
180-
// it if we must and, otherwise, simple use our decode function.
181-
if !p.useJSONNumber {
182-
// JSON Unmarshal. Special case for map type to avoid weird pointer behavior.
183-
if c, ok := token.Claims.(MapClaims); ok {
184-
err = unmarshal(claimBytes, &c)
185-
} else {
186-
err = unmarshal(claimBytes, &claims)
181+
// it if we must and, otherwise, simple use our existing unmarshal function.
182+
if p.useJSONNumber {
183+
unmarshal = func(data []byte, v any) error {
184+
decoder := json.NewDecoder(bytes.NewBuffer(claimBytes))
185+
decoder.UseNumber()
186+
return decoder.Decode(v)
187187
}
188+
}
189+
190+
// JSON Unmarshal the claims. Special case for map type to avoid weird
191+
// pointer behavior.
192+
if c, ok := token.Claims.(MapClaims); ok {
193+
err = unmarshal(claimBytes, &c)
188194
} else {
189-
dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
190-
dec.UseNumber()
191-
// JSON Decode. Special case for map type to avoid weird pointer behavior.
192-
if c, ok := token.Claims.(MapClaims); ok {
193-
err = dec.Decode(&c)
194-
} else {
195-
err = dec.Decode(&claims)
196-
}
195+
err = unmarshal(claimBytes, &claims)
197196
}
198197
if err != nil {
199198
return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err)

0 commit comments

Comments
 (0)