How do I implement pagination for APIs in Go?

Implementing pagination for APIs in Go is essential for managing data efficiently. Pagination allows clients to fetch data in smaller chunks rather than loading everything at once, improving performance and user experience.
pagination, Go API, data management, efficient loading, performance boost
package main import ( "encoding/json" "net/http" "strconv" "github.com/gorilla/mux" ) type Item struct { ID int `json:"id"` Name string `json:"name"` } var items []Item func main() { for i := 1; i <= 100; i++ { items = append(items, Item{ID: i, Name: "Item " + strconv.Itoa(i)}) } r := mux.NewRouter() r.HandleFunc("/items", getItems).Methods("GET") http.ListenAndServe(":8080", r) } func getItems(w http.ResponseWriter, r *http.Request) { pageStr := r.URL.Query().Get("page") limitStr := r.URL.Query().Get("limit") page, _ := strconv.Atoi(pageStr) limit, _ := strconv.Atoi(limitStr) if page < 1 { page = 1 } if limit < 1 { limit = 10 // default limit } start := (page - 1) * limit end := start + limit if start >= len(items) { start = len(items) } if end > len(items) { end = len(items) } json.NewEncoder(w).Encode(items[start:end]) }

pagination Go API data management efficient loading performance boost