6
6
)
7
7
8
8
// Framework version string
9
- const Version = "0.6 "
9
+ const Version = "0.7 "
10
10
11
11
// Yarf is the main entry point for the framework and it centralizes most of the functionality.
12
12
// All configuration actions are handled by this object.
@@ -36,6 +36,9 @@ type Yarf struct {
36
36
37
37
// Follow defines a standard http.Handler implementation to follow if no route matches.
38
38
Follow http.Handler
39
+
40
+ // NotFound defines a function interface to execute when a NotFound error is thrown.
41
+ NotFound func (c * Context )
39
42
}
40
43
41
44
// New creates a new yarf and returns a pointer to it.
@@ -55,7 +58,7 @@ func New() *Yarf {
55
58
// ServeHTTP Implements http.Handler interface into yarf.
56
59
// Initializes a Context object and handles middleware and route actions.
57
60
// If an error is returned by any of the actions, the flow is stopped and a response is sent.
58
- // If no route matches, tries to forward the request to the Yarf.Follow (http.Handler type) property if set.
61
+ // If no route matches, tries to forward the request to the Yarf.Follow (http.Handler type) property if set.
59
62
// Otherwise it returns a 404 response.
60
63
func (y * Yarf ) ServeHTTP (res http.ResponseWriter , req * http.Request ) {
61
64
if y .PanicHandler != nil {
@@ -89,21 +92,26 @@ func (y *Yarf) ServeHTTP(res http.ResponseWriter, req *http.Request) {
89
92
y .log (err , c )
90
93
return
91
94
}
92
-
93
- // Log follow
94
- y .log (nil , c )
95
-
95
+
96
96
// Follow extensions pipe
97
97
if y .Follow != nil {
98
+ // Log follow
99
+ y .log (nil , c )
100
+
101
+ // Follow
98
102
y .Follow .ServeHTTP (c .Response , c .Request )
99
-
103
+
104
+ // End here
100
105
return
101
106
}
102
107
103
108
// Return 404
104
- c . Response . WriteHeader ( 404 )
109
+ y . log ( ErrorNotFound (), c )
105
110
}
106
111
112
+ // Log handles the end of the execution.
113
+ // It checks for errors and custom actions to execute.
114
+ // It also handles the custom 404 error handler.
107
115
func (y * Yarf ) log (err error , c * Context ) {
108
116
// If a logger is present, lets log everything.
109
117
if y .Logger != nil {
@@ -135,8 +143,9 @@ func (y *Yarf) log(err error, c *Context) {
135
143
// Write error data to response.
136
144
c .Response .WriteHeader (yerr .Code ())
137
145
146
+ // Render errors if debug enabled
138
147
if y .Debug {
139
- c .Response . Write ([] byte ( yerr .Body () ))
148
+ c .Render ( yerr .Body ())
140
149
}
141
150
142
151
// Log errors
@@ -147,6 +156,11 @@ func (y *Yarf) log(err error, c *Context) {
147
156
yerr .Body (),
148
157
)
149
158
}
159
+
160
+ // Custom 404
161
+ if yerr .Code () == 404 && y .NotFound != nil {
162
+ y .NotFound (c )
163
+ }
150
164
}
151
165
152
166
// Start initiates a new http yarf server and start listening.
0 commit comments