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
87
88
|
package Messages
import (
"github.com/gorilla/context"
"fmt"
"net/http"
)
const MessagesKey = "messages"
type Messages struct {
Errors map[string][]string
Infos map[string][]string
r *http.Request
}
func GetMessages(r *http.Request) *Messages {
if rv := context.Get(r, MessagesKey); rv != nil {
return rv.(*Messages)
} else {
context.Set(r, MessagesKey, &Messages{})
return &Messages{make(map[string][]string),make(map[string][]string), r}
}
}
func (mes *Messages) AddError(name string, msg string) {
if (mes.Errors == nil) {
mes.Errors = make(map[string][]string)
}
mes.Errors[name] = append(mes.Errors[name], msg)
mes.setMessagesInContext()
}
func (mes *Messages) AddErrorf( name string, msg string, args ...interface{}) {
mes.AddError(name, fmt.Sprintf(msg, args...))
}
func (mes *Messages) ImportFromError(name string, err error) {
mes.AddError(name, err.Error())
}
func (mes *Messages) AddInfo(name string, msg string) {
if (mes.Infos == nil) {
mes.Infos = make(map[string][]string)
}
mes.Infos[name] = append(mes.Infos[name], msg)
mes.setMessagesInContext()
}
func (mes *Messages) AddInfof(name string, msg string, args ...interface{}) {
mes.AddInfo(name, fmt.Sprintf(msg, args...))
}
func (mes *Messages) ClearErrors() {
mes.Infos = nil
mes.setMessagesInContext()
}
func (mes *Messages) ClearInfos() {
mes.Errors = nil
mes.setMessagesInContext()
}
func (mes *Messages) GetAllErrors() map[string][]string {
mes = GetMessages(mes.r) // We need to look if any new errors from other functions has updated context
return mes.Errors
}
func (mes *Messages) GetErrors(name string) []string {
mes = GetMessages(mes.r) // We need to look if any new errors from other functions has updated context
return mes.Errors[name]
}
func (mes *Messages) GetAllInfos() map[string][]string {
mes = GetMessages(mes.r) // We need to look if any new errors from other functions has updated context
return mes.Infos
}
func (mes *Messages) GetInfos(name string) []string {
mes = GetMessages(mes.r) // We need to look if any new errors from other functions has updated context
return mes.Infos[name]
}
func (mes *Messages) HasErrors() bool {
mes = GetMessages(mes.r) // We need to look if any new errors from other functions has updated context
return len(mes.Errors) > 0
}
func (mes *Messages) HasInfos() bool {
mes = GetMessages(mes.r) // We need to look if any new errors from other functions has updated context
return len(mes.Infos) > 0
}
func (mes *Messages) setMessagesInContext() {
context.Set(mes.r, MessagesKey, mes)
}
|