Created
December 15, 2021 12:50
-
-
Save craftamap/83bfba9be337f826853d3ad6e7150e9b to your computer and use it in GitHub Desktop.
REST API pagination with generics in go 1.18beta1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"log" | |
"net/http" | |
) | |
type Spaceship struct { | |
Name string `json:"name"` | |
Length string `json:"length"` | |
} | |
type Person struct { | |
Name string `json:"name"` | |
Height string `json:"height"` | |
} | |
type Response[T any] struct { | |
Count int `` | |
Next string | |
Results []T | |
} | |
func paginate[T any](url string) ([]T, error) { | |
next := url | |
responseItems := []T{} | |
for next != "" { | |
response, err := http.Get(next) | |
if err != nil { | |
return []T{}, nil | |
} | |
var r Response[T]; | |
err = json.NewDecoder(response.Body).Decode(&r) | |
if err != nil { | |
return []T{}, nil | |
} | |
for _, item := range r.Results { | |
responseItems = append(responseItems, item) | |
} | |
next = r.Next | |
} | |
return responseItems, nil | |
} | |
func main() { | |
people, err := paginate[Person]("https://swapi.py4e.com/api/people") | |
log.Println("people", people, err) | |
ships, err := paginate[Spaceship]("https://swapi.py4e.com/api/starships") | |
log.Println("ships", ships, err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment