fix index out of range error (#4998)

dev
Tarun Koyalwar 2024-04-08 14:11:32 +05:30 committed by GitHub
parent 392fb61e94
commit b86fcb5546
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 25 additions and 10 deletions

View File

@ -94,20 +94,35 @@ func (f *Form) Encode(data KV) (string, error) {
} }
} }
} }
if maxIndex >= 0 { // Ensure the slice is only created if maxIndex is valid
data := make([]string, maxIndex+1) // Ensure the slice is large enough data := make([]string, maxIndex+1) // Ensure the slice is large enough
for key, value := range v { for key, value := range v {
matches := reNormalized.FindStringSubmatch(key) matches := reNormalized.FindStringSubmatch(key)
if len(matches) == 2 { if len(matches) == 2 {
dataIdx, _ := strconv.Atoi(matches[1]) // Error already checked above dataIdx, err := strconv.Atoi(matches[1]) // Error already checked above
if err != nil {
gologger.Verbose().Msgf("error converting data index to integer: %v", err)
continue
}
// Validate dataIdx to avoid index out of range errors
if dataIdx > 0 && dataIdx <= len(data) {
data[dataIdx-1] = value // Use dataIdx-1 since slice is 0-indexed data[dataIdx-1] = value // Use dataIdx-1 since slice is 0-indexed
} else {
gologger.Verbose().Msgf("data index out of range: %d", dataIdx)
} }
} }
}
if len(params.Get(k)) > 0 {
data[maxIndex] = fmt.Sprint(params.Get(k)) // Use maxIndex which is the last index data[maxIndex] = fmt.Sprint(params.Get(k)) // Use maxIndex which is the last index
}
// remove existing // remove existing
params.Del(k) params.Del(k)
if len(data) > 0 {
params.Add(k, data...) params.Add(k, data...)
} }
} }
}
}
encoded := params.Encode() encoded := params.Encode()
return encoded, nil return encoded, nil