Skip to content
This repository has been archived by the owner on Jun 2, 2024. It is now read-only.

Commit

Permalink
Handle empty slice and non-slice types in user handler
Browse files Browse the repository at this point in the history
This fix ensures that in the user handler, the records variable is checked if it's a valid slice type before subsetting. If the records variable is empty or not a slice, an error is returned to the client or an empty subset is returned accordingly. This corrects a runtime panic when an invalid or empty slice was passed.
  • Loading branch information
930C committed Jan 18, 2024
1 parent 8e974a9 commit 30a164b
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions internal/routing/handlers/user_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"math/rand"
"net/http"
"reflect"
"strconv"
"time"

Expand Down Expand Up @@ -1008,8 +1009,24 @@ func sendPaginatedResponse(w http.ResponseWriter, records interface{}, offset, l
end = totalRecords
}

// Get the subset
subset := records.([]interface{})[offset:end]
// Get a reflect.Value of records.
v := reflect.ValueOf(records)

// Check if v is not a slice.
if v.Kind() != reflect.Slice {
utils.WriteAndLogError(w, schemas.BadRequest, http.StatusBadRequest, errors.New("records not a valid list"))
return
}

var subset interface{}
// subset only if records is not empty
if v.Len() > 0 {
// Use reflect's slice method to get a subset of records.
subset = v.Slice(offset, end).Interface()
} else {
// If the records slice was empty, subset is an empty slice too
subset = records
}

// Create Pagination DTO
paginationDto := schemas.Pagination{
Expand Down

0 comments on commit 30a164b

Please sign in to comment.