From 7b62a82b42e5086e1e8f508f9a2d8ed4ed388c75 Mon Sep 17 00:00:00 2001 From: loveuer Date: Fri, 19 Jan 2024 20:15:36 +0800 Subject: [PATCH] feat: add 404 page --- ctx.go | 2 +- nf.go | 13 +++++++++++++ router.go | 3 +-- util.go | 8 +++----- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/ctx.go b/ctx.go index b1f3f17..1f0b443 100644 --- a/ctx.go +++ b/ctx.go @@ -207,7 +207,7 @@ func (c *Ctx) Writef(format string, values ...interface{}) (int, error) { } func (c *Ctx) JSON(data interface{}) error { - c.SetHeader("Content-Type", "application/json") + c.SetHeader("Content-Type", MIMEApplicationJSON) encoder := json.NewEncoder(c.writer) diff --git a/nf.go b/nf.go index f489cc6..5285476 100644 --- a/nf.go +++ b/nf.go @@ -2,6 +2,7 @@ package nf const ( banner = " _ _ _ ___ _ \n | \\| |___| |_ | __|__ _ _ _ _ __| |\n | .` / _ \\ _| | _/ _ \\ || | ' \\/ _` |\n |_|\\_\\___/\\__| |_|\\___/\\_,_|_||_\\__,_|\n " + _404 = "Not Found" ) type Map map[string]interface{} @@ -17,11 +18,18 @@ type Config struct { DisableLogger bool `json:"-"` DisableRecover bool `json:"-"` DisableHttpErrorLog bool `json:"-"` + + NotFoundHandler HandlerFunc `json:"-"` } var ( defaultConfig = &Config{ BodyLimit: 4 * 1024 * 1024, + NotFoundHandler: func(c *Ctx) error { + c.Set("Content-Type", MIMETextHTML) + _, err := c.Status(404).Write([]byte(_404)) + return err + }, } ) @@ -35,6 +43,11 @@ func New(config ...Config) *App { if app.config.BodyLimit == 0 { app.config.BodyLimit = defaultConfig.BodyLimit } + + if app.config.NotFoundHandler == nil { + app.config.NotFoundHandler = defaultConfig.NotFoundHandler + } + } else { app.config = defaultConfig } diff --git a/router.go b/router.go index 27cd344..d796f8d 100644 --- a/router.go +++ b/router.go @@ -91,8 +91,7 @@ func (r *router) handle(c *Ctx) error { key := c.Method + "-" + node.pattern c.handlers = append(c.handlers, r.handlers[key]...) } else { - _, err := c.Writef("404 NOT FOUND: %s\n", c.path) - return err + return c.app.config.NotFoundHandler(c) } return c.Next() diff --git a/util.go b/util.go index c336ded..5fdc6a1 100644 --- a/util.go +++ b/util.go @@ -13,11 +13,9 @@ const ( MIMETextJavaScript = "text/javascript" MIMEApplicationXML = "application/xml" MIMEApplicationJSON = "application/json" - // Deprecated: use MIMETextJavaScript instead - MIMEApplicationJavaScript = "application/javascript" - MIMEApplicationForm = "application/x-www-form-urlencoded" - MIMEOctetStream = "application/octet-stream" - MIMEMultipartForm = "multipart/form-data" + MIMEApplicationForm = "application/x-www-form-urlencoded" + MIMEOctetStream = "application/octet-stream" + MIMEMultipartForm = "multipart/form-data" MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8" MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8"