feat: Add response utilities with pagination support and enhance response structures
This commit is contained in:
parent
2db31dc017
commit
c6644aa38e
|
|
@ -23,3 +23,11 @@ func StringToUint(s string) uint {
|
||||||
}
|
}
|
||||||
return uint(id)
|
return uint(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ParseInt(s string) int {
|
||||||
|
i, err := strconv.Atoi(s)
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
package utils
|
package utils
|
||||||
|
|
||||||
|
import "net/http"
|
||||||
|
|
||||||
type Response struct {
|
type Response struct {
|
||||||
Status bool `json:"status"`
|
Status bool `json:"status"`
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
|
|
@ -8,6 +10,14 @@ type Response struct {
|
||||||
Meta any `json:"meta,omitempty"`
|
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{}
|
type EmptyObj struct{}
|
||||||
|
|
||||||
func BuildResponseSuccess(message string, data any) Response {
|
func BuildResponseSuccess(message string, data any) Response {
|
||||||
|
|
@ -28,3 +38,33 @@ func BuildResponseFailed(message string, err string, data any) Response {
|
||||||
}
|
}
|
||||||
return res
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue