From c6644aa38e596a0556c2287e6fcadb7e0d5f6725 Mon Sep 17 00:00:00 2001 From: Habib Fatkhul Rohman Date: Tue, 28 Oct 2025 13:52:36 +0700 Subject: [PATCH] feat: Add response utilities with pagination support and enhance response structures --- pkg/utils/conv.go | 8 ++++++++ pkg/utils/response.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/pkg/utils/conv.go b/pkg/utils/conv.go index 7b507ad..8cd5e78 100644 --- a/pkg/utils/conv.go +++ b/pkg/utils/conv.go @@ -23,3 +23,11 @@ func StringToUint(s string) uint { } return uint(id) } + +func ParseInt(s string) int { + i, err := strconv.Atoi(s) + if err != nil { + return 0 + } + return i +} diff --git a/pkg/utils/response.go b/pkg/utils/response.go index e47ae44..e1fe21d 100644 --- a/pkg/utils/response.go +++ b/pkg/utils/response.go @@ -1,5 +1,7 @@ package utils +import "net/http" + type Response struct { Status bool `json:"status"` Message string `json:"message"` @@ -8,6 +10,14 @@ type Response struct { Meta any `json:"meta,omitempty"` } +type ResponseWithPagination struct { + Code int `json:"code"` + Status string `json:"status"` + Message string `json:"message"` + Data interface{} `json:"data"` + Pagination PaginationResponse `json:"pagination"` +} + type EmptyObj struct{} func BuildResponseSuccess(message string, data any) Response { @@ -28,3 +38,33 @@ func BuildResponseFailed(message string, err string, data any) Response { } return res } + +type PaginationResponse struct { + Page int `json:"page"` + PerPage int `json:"per_page"` + MaxPage int `json:"max_page"` + Total int64 `json:"total"` +} + +func BuildPaginationResponse(perPage, page int, total int64) PaginationResponse { + maxPage := 1 + if perPage > 0 { + maxPage = int((total + int64(perPage) - 1) / int64(perPage)) + } + return PaginationResponse{ + Page: page, + PerPage: perPage, + MaxPage: maxPage, + Total: total, + } +} + +func BuildResponseSuccessWithPagination(code int, message string, data interface{}, pagination PaginationResponse) ResponseWithPagination { + return ResponseWithPagination{ + Code: code, + Status: http.StatusText(code), + Message: message, + Data: data, + Pagination: pagination, + } +}