-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
50 lines (41 loc) · 869 Bytes
/
api.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
50
package protocol
import (
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"net/http"
)
var (
Success = 0
BlockFailure = 10001
TxnFailure = 10002
ReceiptFailure = 10003
)
type APIResponse struct {
Code int `json:"code"`
ErrMsg string `json:"err_msg"`
Data any `json:"data"`
}
func (a *APIResponse) IsSuccess() bool {
return a.Code == Success
}
func (a *APIResponse) Error() error {
return errors.New(a.ErrMsg)
}
func RenderSuccess(ctx *gin.Context, data any) {
RenderJson(ctx, Success, nil, data)
}
func RenderError(ctx *gin.Context, code int, err error) {
RenderJson(ctx, code, err, nil)
}
func RenderJson(ctx *gin.Context, code int, err error, data any) {
var errMsg string
if err != nil {
errMsg = err.Error()
}
resp := APIResponse{
Code: code,
ErrMsg: errMsg,
Data: data,
}
ctx.JSON(http.StatusOK, resp)
}