-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpUtils.go
49 lines (43 loc) · 991 Bytes
/
httpUtils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package utils
import (
"errors"
"gorm.io/gorm"
)
type HTTPResponse struct {
Status int `json:"status"`
Data any `json:"data"`
Meta map[string]interface{} `json:"meta,omitempty"`
}
type HTTPError struct {
Message string `json:"message"`
}
type HTTPErrorResponse struct {
Status int `json:"status"`
Error HTTPError `json:"error"`
}
func NewHTTPResponse(status int, data any, meta ...map[string]interface{}) (int, *HTTPResponse) {
var metaData map[string]interface{}
if meta != nil {
metaData = meta[0]
}
return status, &HTTPResponse{
Status: status,
Data: data,
Meta: metaData,
}
}
func NewHTTPErrorResponse(err error, status ...int) (int, *HTTPErrorResponse) {
httpStatus := 500
if status != nil {
httpStatus = status[0]
}
if errors.Is(err, gorm.ErrRecordNotFound) {
httpStatus = 404
}
return httpStatus, &HTTPErrorResponse{
Status: httpStatus,
Error: HTTPError{
Message: err.Error(),
},
}
}