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

如何在不使用DefaultServeMux的情况下实现HandlerFunc

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

如何在不使用DefaultServeMux的情况下实现HandlerFunc

将您的授权中间件重新实现为

http.Handler

type auth struct {   DB *sql.DB   UnauthorizedHandler http.Handler}func NewAuth(db *sql.DB, unauthorized http.Handler) *auth {    return auth{db, unauthorized}}func (a *auth) Protected(h http.Handler) http.Handler {    fn := func(w http.ResponseWriter, r *http.Request) {        // Check whether the request is valid        // If it's invalid, call your error func and make sure to *return* early!        if !valid { a.UnauthorizedHandler.ServeHTTP(w, r) return        }        // Call the next handler on success        h.ServeHTTP(w, r)        return    }    return http.HandlerFunc(fn)}func someHandler(w http.ResponseWriter, r *http.Request) {    io.WriteString(w, "Hello!n")}func main() {    auth := NewAuth(db, errorHandler)    r := http.NewServeMux()    // We have a http.Handler implementation that wraps a http.HandlerFunc    // ... so we call r.Handle on our ServeMux and type-cast the wrapped func    r.Handle("/protected", auth.Protected(http.HandlerFunc(someHandler)))    // Just a simple http.HandlerFunc here    r.HandleFunc("/public", someOtherHandler)    log.Fatal(http.ListenAndServe(":8000", r))}

Take a look at the httpauth lib I
wrote
for a
different example with a

ServeHTTP
method. Both the above and explicitly
creating a
ServeHTTP
method on your type are valid approaches.



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

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

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