栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

httprouter配置NotFound

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

httprouter配置NotFound

类型

httprouter.Router
struct
具有字段的:

NotFound http.Handler

因此,类型为,

NotFound
http.Handler
一种具有单个方法的接口类型:

ServeHTTP(ResponseWriter, *Request)

如果要使用自己的自定义“未找到”处理程序,则必须设置一个实现此接口的值。

最简单的方法是使用签名定义函数:

func(http.ResponseWriter, *http.Request)

并使用

http.HandlerFunc()
辅助函数将其“转换”为实现
http.Handler
接口的值,该接口的
ServeHTTP()
方法仅使用上述签名调用该函数。

例如:

func MyNotFound(w http.ResponseWriter, r *http.Request) {    w.Header().Set("Content-Type", "text/plain; charset=utf-8")    w.WriteHeader(http.StatusNotFound) // StatusNotFound = 404    w.Write([]byte("My own Not Found handler."))    w.Write([]byte(" The page you requested could not be found."))}var router *httprouter.Router = ... // Your router valuerouter.NotFound = http.HandlerFunc(MyNotFound)

NotFound
处理程序将由
httprouter
包调用。如果要从其他处理程序之一手动调用它,则必须将a
ResponseWriter
和a
传递
*Request
给它,如下所示:

func ResourceHandler(w http.ResponseWriter, r *http.Request) {    exists := ... // Find out if requested resource is valid and available    if !exists {        MyNotFound(w, r) // Pass ResponseWriter and Request        // Or via the Router:        // router.NotFound(w, r)        return    }    // Resource exists, serve it    // ...}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/468994.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号