-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
73 lines (63 loc) · 1.59 KB
/
handler.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package ginfmt
import (
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"github.com/sleagon/ginfmt/errfmt"
)
var logger Logger = logrus.New()
const respKey = "$$X_GINFMT_RESP_KEY$$"
// Handler ginfmt handler
// the interface{} will be set to data field in response body
// the error will be transformed to some specific response body
type Handler func(c *gin.Context) (interface{}, error)
type Logger interface {
Error(args ...interface{})
Errorf(format string, args ...interface{})
Warn(args ...interface{})
Warnf(format string, args ...interface{})
Info(args ...interface{})
Infof(format string, args ...interface{})
Debug(args ...interface{})
Debugf(format string, args ...interface{})
}
// Init init ginfmt with log and i18n translator
func Init(log Logger, trans errfmt.Translator) {
if log != nil {
logger = log
}
if trans != nil {
errfmt.Init(trans)
}
}
// Data set data field of response
func Data(c *gin.Context, data interface{}) {
body, ok := c.Get(respKey)
if ok && body != nil {
logger.Warnf("Response body has been written")
return
}
c.Set(respKey, data)
}
// Error set response error
func Error(c *gin.Context, err error) {
if err == nil {
return
}
c.Error(err) // nolint: errcheck
}
// DataError Set response data and error at the same time.
func DataError(c *gin.Context, data interface{}, err error) {
if data != nil {
Data(c, data)
}
if err != nil {
Error(c, err)
}
}
// NewHandlderFunc build a gin#HandlerFunc based on Handler
func NewHandlerFunc(h Handler) gin.HandlerFunc {
return func(c *gin.Context) {
d, e := h(c)
DataError(c, d, e)
}
}