I recently ran into a problem with developing Web applications using Golang.
I wrote an interface to filter a list of people’s credentials.
http://127.0.0.1:11088/api/v1/person-auths?status=0,2
Copy the code
The status field is a filter condition. For example, 0 and 2 are used to query authentication records of all personnel whose status is 0 and 2.
In the GIN framework, you can use ctx.query to retrieve the string corresponding to status.
statusStr := ctx.Query("status")/ / 1, 2
Copy the code
The query parameter structure type for the business logic layer defines this:
type PersonAuthQueryParam struct {
Status []int
// ...
}
Copy the code
So I need to convert the string 1,2 to a slice of int [1, 2].
By JavaScript convention, this is pretty simple.
statusStr := "1, 2,"
statusStrs := strings.Split(statusStr, ",")
var statusInts []int
for i, v := range statusStrs {
vInt, err := strconv.Atoi(v)
iferr ! =nil {
return err
}
statusInts[i] = vInt
}
Copy the code
The logic is to split the string into a string slice and then create an empty int slice. Iterating over the string slice, converting the type of each element to int and assigning the value above the corresponding index of the int slice.
But at actual runtime, you get a Runtime error.
panic: runtime error: index out of range [0] with length 0
Copy the code
This is a standard array out of bounds problem.
Because the int slice is empty, its length and capacity are both 0.
fmt.Printf("%v\n".len(statusInts))/ / 0
fmt.Printf("%v\n".cap(statusInts))/ / 0
fmt.Printf("%v\n", statusInts == nil)// true
Copy the code
There are two ways to solve this.
The first is to add elements in a different way.
Use the append function to add elements, and it automatically expands.
statusInts = append(statusInts, vInt)
Copy the code
The second option is to initialize the slice in a different way by giving the slice a length.
statusInts := make([]int.len(statusStrs))
Copy the code