gpt4 book ai didi

http - 如何使文件系统为http.Handler

转载 作者:行者123 更新时间:2023-12-01 20:26:26 25 4
gpt4 key购买 nike

我想在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。现在,如果我将此处理程序包装在fileSystem周围,应该如何对其进行编码?

最佳答案

您可以使用闭包:

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 - 如何使文件系统为http.Handler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61909818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com