Add 404 error handling

This commit is contained in:
paku 2024-04-14 22:57:19 +09:00
parent e84b170a03
commit 79496d5900
2 changed files with 33 additions and 15 deletions

View file

@ -20,7 +20,7 @@ To use ningle-fbr, you must use [package-inferred-system](https://asdf.common-li
`/src/app.lisp`
```lisp
(uiop:define-package #:example
(defpackage #:example
(:nicknames #:example/app)
(:use #:cl)
(:import-from #:ningle)
@ -46,7 +46,7 @@ To use ningle-fbr, you must use [package-inferred-system](https://asdf.common-li
`/src/routes/nested/page.lisp``/nested/page`
```lisp
(uiop:define-package #:example/routes/index
(defpackage #:example/routes/index
(:use #:cl)
(:export #:handle-get
#:handle-post
@ -75,6 +75,20 @@ In the example below, the parameter `id` can be obtained from handler's params.
`/src/routes/user/=id.lisp``/user/:id`
## Not found error
`not-found.lisp` is a special file to handle 404 errors. Implement `handle-not-found` function and export it.
```lisp
(defpackage #:example/routes/not-found
(:use #:cl)
(:export #:handle-not-found))
(in-package #:example/routes/not-found)
(defun handle-not-found ()
...)
```
# License
Licensed under MIT License. 

View file

@ -1,36 +1,36 @@
(uiop:define-package :ningle-fbr
(:nicknames #:ningle-fbr/main)
(:use #:cl)
(:local-nicknames (#:re #:cl-ppcre))
(:local-nicknames (#:ng #:ningle))
(:import-from #:cl-ppcre)
(:import-from #:ningle)
(:export #:assign-routes))
(in-package :ningle-fbr)
(defun remove-file-type (namestr)
(re:regex-replace ".lisp" namestr ""))
(cl-ppcre:regex-replace ".lisp" namestr ""))
(defun remove-index (url)
(if (string= url "/index")
"/"
(re:regex-replace "/index" url "")))
(cl-ppcre:regex-replace "/index" url "")))
(defun replace-dynamic-annotation (url)
(re:regex-replace "=" url ":"))
(cl-ppcre:regex-replace "=" url ":"))
(defun format-url (url)
(replace-dynamic-annotation (remove-index url)))
(defun pathname->url (pathname dir-namestring)
(format-url
(re:regex-replace dir-namestring
(remove-file-type (namestring pathname))
"")))
(cl-ppcre:regex-replace dir-namestring
(remove-file-type (namestring pathname))
"")))
(defun pathname->package (pathname system-path-namestring system-prefix)
(string-upcase
(re:regex-replace system-path-namestring
(remove-file-type (namestring pathname))
system-prefix)))
(cl-ppcre:regex-replace system-path-namestring
(remove-file-type (namestring pathname))
system-prefix)))
(defun dir->pathnames (dir)
(directory (concatenate 'string
@ -56,9 +56,13 @@
(loop
:for (url . pkg) :in (dir->urls-and-packages directory system)
:do (ql:quickload pkg)
(if (string= url "/not-found")
(let ((handler (find-symbol "HANDLE-NOT-FOUND" pkg)))
(defmethod ningle:not-found ((app ningle:app))
(funcall handler))))
(loop
:for method :in *http-request-methods*
:do (let ((handler (find-symbol (concatenate 'string "HANDLE-" (string method))
pkg)))
(when handler
(setf (ng:route app url :method method) handler))))))
(setf (ningle:route app url :method method) handler))))))