/
rout_err.go
99 lines (85 loc) · 2.55 KB
/
rout_err.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
87
88
89
90
91
92
93
94
95
96
97
98
99
package rout
import (
"fmt"
"net/http"
"strconv"
)
/*
Returned by `rout.Route` when the router wasn't properly initialized. Using
`rout.MakeRou` avoids this.
*/
var ErrInit = fmt.Errorf(
`[rout] routing error: the router wasn't properly initialized; please use "rout.MakeRou"`,
)
// Error type returned by `rout.Route` for requests with a known path and an
// unknown method.
type ErrMethodNotAllowed string
// Implement a hidden interface supported by `rout.ErrStatus`.
// Always returns `http.StatusMethodNotAllowed`.
func (ErrMethodNotAllowed) HttpStatusCode() int { return http.StatusMethodNotAllowed }
// Implement `error` by returning self.
func (self ErrMethodNotAllowed) Error() string { return string(self) }
// Error type returned by `rout.Route` for requests with an unknown path.
type ErrNotFound string
// Implement a hidden interface supported by `rout.ErrStatus`.
// Always returns `http.StatusNotFound`.
func (ErrNotFound) HttpStatusCode() int { return http.StatusNotFound }
// Implement `error` by returning self.
func (self ErrNotFound) Error() string { return string(self) }
// Generates an appropriate `ErrMethodNotAllowed`. Used internally.
func MethodNotAllowed(meth, path string) ErrMethodNotAllowed {
return ErrMethodNotAllowed(Err(
`method not allowed`, ErrMethodNotAllowed(``).HttpStatusCode(), meth, path,
))
}
// Generates an appropriate `ErrNotFound`. Used internally.
func NotFound(meth, path string) ErrNotFound {
return ErrNotFound(Err(
`no such endpoint`, ErrNotFound(``).HttpStatusCode(), meth, path,
))
}
/*
Generates a routing error message including the given status, method and path.
More efficient than equivalent `fmt.Sprintf` or `fmt.Errorf`.
*/
func Err(msg string, status int, meth, path string) string {
const (
preface = `[rout] routing error`
statusPrefix = ` (HTTP status `
statusSuffix = `)`
colon = `: `
quote = `"`
quoteInfix = `" "`
)
buf := make(
[]byte,
0,
len(preface)+
len(statusPrefix)+
intLen(status)+
len(statusSuffix)+
len(colon)+
len(msg)+
len(colon)+
len(quote)+
len(meth)+
len(quoteInfix)+
len(path)+
len(quote),
)
buf = append(buf, preface...)
if status != 0 {
buf = append(buf, statusPrefix...)
buf = strconv.AppendInt(buf, int64(status), 10)
buf = append(buf, statusSuffix...)
}
buf = append(buf, colon...)
buf = append(buf, msg...)
buf = append(buf, colon...)
buf = append(buf, quote...)
buf = append(buf, meth...)
buf = append(buf, quoteInfix...)
buf = append(buf, path...)
buf = append(buf, quote...)
return bytesString(buf)
}