Skip to content

Commit b9e088b

Browse files
Add NotFound handler
1 parent a98ca60 commit b9e088b

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

yarf.go

+23-9
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
)
77

88
// Framework version string
9-
const Version = "0.6"
9+
const Version = "0.7"
1010

1111
// Yarf is the main entry point for the framework and it centralizes most of the functionality.
1212
// All configuration actions are handled by this object.
@@ -36,6 +36,9 @@ type Yarf struct {
3636

3737
// Follow defines a standard http.Handler implementation to follow if no route matches.
3838
Follow http.Handler
39+
40+
// NotFound defines a function interface to execute when a NotFound error is thrown.
41+
NotFound func(c *Context)
3942
}
4043

4144
// New creates a new yarf and returns a pointer to it.
@@ -55,7 +58,7 @@ func New() *Yarf {
5558
// ServeHTTP Implements http.Handler interface into yarf.
5659
// Initializes a Context object and handles middleware and route actions.
5760
// 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.
5962
// Otherwise it returns a 404 response.
6063
func (y *Yarf) ServeHTTP(res http.ResponseWriter, req *http.Request) {
6164
if y.PanicHandler != nil {
@@ -89,21 +92,26 @@ func (y *Yarf) ServeHTTP(res http.ResponseWriter, req *http.Request) {
8992
y.log(err, c)
9093
return
9194
}
92-
93-
// Log follow
94-
y.log(nil, c)
95-
95+
9696
// Follow extensions pipe
9797
if y.Follow != nil {
98+
// Log follow
99+
y.log(nil, c)
100+
101+
// Follow
98102
y.Follow.ServeHTTP(c.Response, c.Request)
99-
103+
104+
// End here
100105
return
101106
}
102107

103108
// Return 404
104-
c.Response.WriteHeader(404)
109+
y.log(ErrorNotFound(), c)
105110
}
106111

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.
107115
func (y *Yarf) log(err error, c *Context) {
108116
// If a logger is present, lets log everything.
109117
if y.Logger != nil {
@@ -135,8 +143,9 @@ func (y *Yarf) log(err error, c *Context) {
135143
// Write error data to response.
136144
c.Response.WriteHeader(yerr.Code())
137145

146+
// Render errors if debug enabled
138147
if y.Debug {
139-
c.Response.Write([]byte(yerr.Body()))
148+
c.Render(yerr.Body())
140149
}
141150

142151
// Log errors
@@ -147,6 +156,11 @@ func (y *Yarf) log(err error, c *Context) {
147156
yerr.Body(),
148157
)
149158
}
159+
160+
// Custom 404
161+
if yerr.Code() == 404 && y.NotFound != nil {
162+
y.NotFound(c)
163+
}
150164
}
151165

152166
// Start initiates a new http yarf server and start listening.

0 commit comments

Comments
 (0)