Go 将文件系统添加到现有http api web服务器的最佳方法
我已经有了一个web服务器,它工作得很好,现在我想向它添加文件系统模块 项目概述如下Go 将文件系统添加到现有http api web服务器的最佳方法,go,Go,我已经有了一个web服务器,它工作得很好,现在我想向它添加文件系统模块 项目概述如下 // Custom router type Handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) error type Middleware func(Handler) Handler type App struct { mux *chi.Mux och *ochttp.Han
// Custom router
type Handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) error
type Middleware func(Handler) Handler
type App struct {
mux *chi.Mux
och *ochttp.Handler
mw []Middleware
}
func NewApp(mw ...Middleware) *App {
app := App{
mux: chi.NewRouter(),
mw: mw,
}
app.och = &ochttp.Handler{
Handler: app.mux,
Propagation: &tracecontext.HTTPFormat{},
}
return &app
}
func (a *App) Handle(verb, path string, handler Handler, mw ...Middleware) {
handler = wrapMiddleware(a.mw, handler)
h := func(w http.ResponseWriter, r *http.Request) {
...
}
a.mux.MethodFunc(verb, path, h)
}
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.och.ServeHTTP(w, r)
}
// route
func API(...) http.Handler {
app := web.NewApp(mid.Logger(log)...)
s := Something{
...
}
app.Handle("GET", "/v1/somthing", s.DoSomething)
return app
}
// Handler
type Something struct {
...
}
func (s *Something) DoSomething(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
...
}
// main
api := http.Server{
...
Handler: API(...),
}
go func() {
api.ListenAndServe()
}()
app struct是一个自定义路由器,它包含第三个路由器、跟踪库和一些中间件。类型处理程序是用于中间件和任何api处理程序注册到此路由器的特定处理程序格式。因为这个项目只硬编码一个处理程序,所以最好向它添加另一个类似文件系统的处理程序。http.Handler和通过闭包转换的处理程序 //处理程序到处理程序 func NewHandlerh http.Handler{ 返回funcctx context.context,w http.ResponseWriter,r*http.Request错误{ h、 ServeHTTPw,r } } //处理程序到http.Handler func NewHTTPHandlerh处理程序http.Handler{ 返回http.handlerfuncw http.ResponseWriter,r*http.Request{ hcontext.Background,w,r } } //或者处理程序实现http.Handler func fn处理程序ServeHTTPw http.ResponseWriter,r*http.Request{ fncontext.Background,w,r } app.HandleANY,/fs/*,NewHandlerhttp.FileServerhttp.Dirpublic 类型处理程序func上下文是最好的处理程序定义。通过http.Request.context或顶级context请求context.context对象。context通过http.Server.BaseContext属性获得 中间件的最佳实现思想是echo或gin框架使用两种方法,但echo方法不应复制内存分配浪费 建议自行实现路由器。在主流框架和路由清单中,没有路由优先级,例如大量库,如echo gin httprouter gorilla/mux 以下是我为22个月设计的框架和最简单的实现 我的web框架:
简单的框架:fei chang gan xie