登录
首页 >  Golang >  Go问答

如何将文件系统设置为 http.Handler

来源:stackoverflow

时间:2024-04-04 16:09:25 189浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《如何将文件系统设置为 http.Handler》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我想在 http.handler 中封装文件系统。

type Handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) error

func (a *App) Handle(verb, path string, handler Handler) {
        ...
        h := func(w http.ResponseWriter, r *http.Request) {
                ...
        }

        a.myRouter.HandleFunc(verb, path, h)
}

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    a.myRouter.ServeHTTP(w, r)
}

func MYAPI(...) http.Handler {
        ...
        app.Handle("Get", "/files", http.StripPrefix(pathPrefix,       http.FileServer(root)))
        return app
}

api := http.Server{
        ...
        Handler:      MYAPI(),
}

该应用程序是我的自定义路由器,我定义了自己的 http.handler handler。现在,如果我将此处理程序包装在文件系统周围,应该如何使用它进行编码?


解决方案


您可以使用闭包:

func FromHTTPHandler(h http.Handler) Handler {
    return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
        h.ServeHTTP(w, r)
        return nil
    }
}

// ...

app.Handle("Get", "/files", FromHTTPHandler(http.StripPrefix(pathPrefix, http.FileServer(root))))

理论要掌握,实操不能落!以上关于《如何将文件系统设置为 http.Handler》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>