HeaderWithFormatter adds an HTTP header for pagination which uses a custom formatter for generating the URL links.
(w http.ResponseWriter, u *url.URL, total int64, page, itemsPerPage int, f formatter)
| 24 | |
| 25 | // HeaderWithFormatter adds an HTTP header for pagination which uses a custom formatter for generating the URL links. |
| 26 | func HeaderWithFormatter(w http.ResponseWriter, u *url.URL, total int64, page, itemsPerPage int, f formatter) { |
| 27 | if itemsPerPage <= 0 { |
| 28 | itemsPerPage = 1 |
| 29 | } |
| 30 | |
| 31 | itemsPerPage64 := int64(itemsPerPage) |
| 32 | offset := int64(page) * itemsPerPage64 |
| 33 | |
| 34 | // lastOffset will either equal the offset required to contain the remainder, |
| 35 | // or the limit. |
| 36 | var lastOffset int64 |
| 37 | if total%itemsPerPage64 == 0 { |
| 38 | lastOffset = total - itemsPerPage64 |
| 39 | } else { |
| 40 | lastOffset = (total / itemsPerPage64) * itemsPerPage64 |
| 41 | } |
| 42 | |
| 43 | w.Header().Set("X-Total-Count", strconv.FormatInt(total, 10)) |
| 44 | |
| 45 | // Check for last page |
| 46 | if offset >= lastOffset { |
| 47 | if total == 0 { |
| 48 | w.Header().Set("Link", strings.Join([]string{ |
| 49 | f(u, "first", itemsPerPage64, 0), |
| 50 | f(u, "next", itemsPerPage64, ((offset/itemsPerPage64)+1)*itemsPerPage64), |
| 51 | f(u, "prev", itemsPerPage64, ((offset/itemsPerPage64)-1)*itemsPerPage64), |
| 52 | }, ",")) |
| 53 | return |
| 54 | } |
| 55 | |
| 56 | if total <= itemsPerPage64 { |
| 57 | w.Header().Set("link", f(u, "first", total, 0)) |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | w.Header().Set("Link", strings.Join([]string{ |
| 62 | f(u, "first", itemsPerPage64, 0), |
| 63 | f(u, "prev", itemsPerPage64, lastOffset-itemsPerPage64), |
| 64 | }, ",")) |
| 65 | return |
| 66 | } |
| 67 | |
| 68 | if offset < itemsPerPage64 { |
| 69 | w.Header().Set("Link", strings.Join([]string{ |
| 70 | f(u, "next", itemsPerPage64, itemsPerPage64), |
| 71 | f(u, "last", itemsPerPage64, lastOffset), |
| 72 | }, ",")) |
| 73 | return |
| 74 | } |
| 75 | |
| 76 | w.Header().Set("Link", strings.Join([]string{ |
| 77 | f(u, "first", itemsPerPage64, 0), |
| 78 | f(u, "next", itemsPerPage64, ((offset/itemsPerPage64)+1)*itemsPerPage64), |
| 79 | f(u, "prev", itemsPerPage64, ((offset/itemsPerPage64)-1)*itemsPerPage64), |
| 80 | f(u, "last", itemsPerPage64, lastOffset), |
| 81 | }, ",")) |
| 82 | } |
| 83 |