-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap_fn.go
86 lines (72 loc) · 1.57 KB
/
map_fn.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
74
75
76
77
78
79
80
81
82
83
84
85
86
package gos
import (
"fmt"
"net/http"
)
const (
keyFieldHttpStatus = "__http_status"
keyFieldHttpRedirect = "__redirect"
keyFieldCode = "code"
keyFieldMsg = "msg"
keyFieldData = "data"
)
func (m *Map) SetData(data interface{}) *Map {
return m.Set(keyFieldData, data)
}
func (m *Map) SetCode(code string) *Map {
if code != "" {
return m.Set(keyFieldCode, code)
}
return m
}
func (m *Map) SetMessage(format string, args ...interface{}) *Map {
if format != "" {
return m.Set(keyFieldMsg, fmt.Sprintf(format, args...))
}
return m
}
func (m *Map) SetEx(err error) *Map {
if err != nil {
m.SetMessage(err.Error())
}
return m
}
func (m *Map) SetStatus(status int) *Map {
if status > 0 {
m.Set(keyFieldHttpStatus, status)
}
return m
}
func (m *Map) PopStatus(status *int) bool {
v, find := m.Get(keyFieldHttpStatus)
if find {
m.Del(keyFieldHttpStatus)
*status = v.(int)
}
return find
}
func (m *Map) Redirect(status *int, redirectTo *string) bool {
m.PopStatus(status)
if *status != http.StatusMovedPermanently && *status != http.StatusTemporaryRedirect {
return false
}
if to, find := m.Get(keyFieldHttpRedirect); find {
if sto, ok := to.(string); ok && sto != "" {
m.Del(keyFieldHttpRedirect)
*redirectTo = sto
return true
}
}
*status = 500
return false
}
func (m *Map) Basic(code, format string, args ...interface{}) *Map {
return m.SetCode(code).SetCode(fmt.Sprintf(format, args...))
}
func (m *Map) Error() string {
var (
code, _ = m.Get(keyFieldCode)
msg, _ = m.Get(keyFieldMsg)
)
return fmt.Sprintf("[%v] %v", code, msg)
}