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

How to make filesystem as 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(),
}

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

您可以使用闭包:

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))))