How to Implement Pagination in a Go API

Web
Implement Go API pagination by parsing query parameters and slicing your data array based on calculated offsets.

Implement pagination by reading page and limit query parameters, calculating the offset, and slicing your data slice before returning it.

func GetItems(w http.ResponseWriter, r *http.Request) {
    page, _ := strconv.Atoi(r.URL.Query().Get("page"))
    limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
    if page < 1 { page = 1 }
    if limit < 1 { limit = 10 }
    offset := (page - 1) * limit
    end := offset + limit
    if end > len(items) { end = len(items) }
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(items[offset:end])
}