-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathctx.go
More file actions
73 lines (64 loc) 路 2.01 KB
/
Copy pathctx.go
File metadata and controls
73 lines (64 loc) 路 2.01 KB
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
// CTX is a web framework which simply use httprouter as its router,
// and offer an easier method (or just alias) of the 'net/http'.
// CTX itself dose not integrate websocket, but if you need this, please go
// check https://github.com/gorilla/websocket or a easier one like
// https://github.com/olahol/melody.
package ctx
import (
"errors"
"fmt"
"net/http"
)
// Map is the alias of map[string]interface{}
type Map map[string]interface{}
// ErrNotFound is the NotFound error.
var ErrNotFound = errors.New("404 Not Found")
// ErrMethodNotAllow is the MethodNotAllowed error.
var ErrMethodNotAllow = errors.New("405 Method Not Allow")
// SuccessCB is the c.Success() callback.
// NOTE: DO NOT USE DEFAULT, MAKE IT YOURS.
var SuccessCB = func(*Context, interface{}) error { return nil }
// ErrorCB is the c.Error() callback.
// NOTE: DO NOT USE DEFAULT, MAKE IT YOURS.
var ErrorCB = func(c *Context, code int, msg interface{}) error {
innerError := ""
switch msg.(type) {
case string:
innerError = msg.(string)
case error:
innerError = msg.(error).Error()
default:
innerError = "internal server error, unsupported error message type"
}
http.Error(c.Res, innerError, code)
return nil
}
// ErrorHandler is the centralized error handler.
// NOTE: DO NOT USE DEFAULT, MAKE IT YOURS.
var ErrorHandler = func(c *Context, err error) {
if err == ErrNotFound {
c.SetStatusCode(http.StatusNotFound)
c.Error(http.StatusNotFound, err)
} else if err == ErrMethodNotAllow {
c.SetStatusCode(http.StatusMethodNotAllowed)
c.Error(http.StatusMethodNotAllowed, err)
} else {
c.SetStatusCode(http.StatusInternalServerError)
c.Error(c.StatusCode, err)
}
}
// PanicHandler is the centralized panic handler.
// NOTE: DO NOT USE DEFAULT, MAKE IT YOURS.
var PanicHandler = func(c *Context, msg interface{}) {
if c.StatusCode == 0 {
c.StatusCode = 500
}
c.Error(c.StatusCode, msg)
}
// e returns a ctx error.
func e(msg string, err error) error {
if err == nil {
return nil
}
return fmt.Errorf("%s %s: %v", "[CTX]", msg, err)
}