Help us shape the future of Go! Take the 2026 Go Developer Survey

bettermux

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 6, 2026 License: MIT Imports: 2 Imported by: 0

README

bettermux | 基于 Go 标准库 http.ServeMux 的分组路由与中间件框架

纯封装 Go 标准库 net/http 的 ServeMux, 仅此而已

开始使用

go get github.com/UnknownMp391/bettermux

要求 Go 1.22+ (使用增强路由特性, 如方法路由与路径参数)

特性

方法路由 Get / Post / Put / Delete / Patch / Options

基于 Go 1.22+ 的增强路由, 内部以 "METHOD /path" 形式注册 pattern, 支持 {name} 路径参数(通过 r.PathValue 读取)

mux := bettermux.NewBetterMux()

mux.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "GET user %s", r.PathValue("id"))
})

mux.Post("/users", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusCreated)
})

mux.Put("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "PUT user %s", r.PathValue("id"))
})

mux.Patch("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "PATCH user %s", r.PathValue("id"))
})

mux.Delete("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "DELETE user %s", r.PathValue("id"))
})

mux.Options("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusNoContent)
})

http.ListenAndServe(":8080", mux)
分组路由 Route 与 Mount

Route 创建独立的子 mux 并挂载到指定前缀下, 子路由拥有自己的命名空间, 可嵌套使用

Mount 将任意 http.Handler 挂载到前缀下, 并自动处理 StripPrefix

mux := bettermux.NewBetterMux()

mux.Route("/api/", func(api *bettermux.BetterMux) {
    api.Get("/users", func(w http.ResponseWriter, r *http.Request) {
        // GET /api/users
    })
    api.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
        // GET /api/users/42
    })
})

// 静态文件: /static/css/app.css → ./static/css/app.css
mux.Mount("/static", http.FileServer(http.Dir("./static")))

http.ListenAndServe(":8080", mux)
中间件 With 与 Handle

With 声明中间件, 可链式调用, 先声明的先执行 (最外层)

通过 Handle / HandleFunc 或任意方法路由注册时, 自动将整条中间件链应用到 handler 上

mux := bettermux.NewBetterMux()

logged := mux.With(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println(">>", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
    })
})

// 链式中间件: 先声明的 Logging 先执行, 再执行 Auth, 最后到达 handler
app := logged.With(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("Authorization") == "" {
            http.Error(w, "unauthorized", http.StatusUnauthorized)
            return
        }
        next.ServeHTTP(w, r)
    })
})

app.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello with middleware"))
})

http.ListenAndServe(":8080", app)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BetterMux

type BetterMux struct {
	// RealMux is the underlying *http.ServeMux that all routes are
	// registered on and that ServeHTTP delegates to.
	RealMux *http.ServeMux

	// ParentMux points to the BetterMux this one was derived from via With,
	// and is used to walk the middleware chain at route registration time.
	// It is nil for a mux created by NewBetterMux or
	// NewBetterMuxWithServeMux.
	ParentMux *BetterMux

	// Middleware is the middleware function declared by With on this mux.
	// It is nil unless the mux was created by With.
	Middleware func(http.Handler) http.Handler
}

BetterMux is a group routing and middleware wrapper around the standard library's http.ServeMux. It has zero runtime overhead: all of its logic runs at route registration time, and serving is delegated entirely to the underlying *http.ServeMux.

The API is inspired by github.com/go-chi/chi.

func NewBetterMux added in v1.1.0

func NewBetterMux() *BetterMux

NewBetterMux returns a new BetterMux backed by a fresh http.ServeMux.

func NewBetterMuxWithServeMux added in v1.1.0

func NewBetterMuxWithServeMux(mux *http.ServeMux) *BetterMux

NewBetterMuxWithServeMux returns a new BetterMux that wraps the given *http.ServeMux. If mux is nil, a new http.ServeMux is created.

func (*BetterMux) Delete

func (mux *BetterMux) Delete(pattern string, handler http.HandlerFunc)

Delete registers handler for the "DELETE <pattern>" pattern, using the Go 1.22+ enhanced ServeMux routing.

func (*BetterMux) Get

func (mux *BetterMux) Get(pattern string, handler http.HandlerFunc)

Get registers handler for the "GET <pattern>" pattern, using the Go 1.22+ enhanced ServeMux routing (pattern may contain wildcards such as "/users/{id}", read via r.PathValue).

func (*BetterMux) Handle

func (mux *BetterMux) Handle(pattern string, handler http.Handler)

Handle registers handler for the given pattern on the underlying http.ServeMux, applying the mux's middleware chain (declared via With) to the handler first.

func (*BetterMux) HandleFunc

func (mux *BetterMux) HandleFunc(pattern string, fn http.HandlerFunc)

HandleFunc registers the handler function fn for the given pattern, equivalent to Handle(pattern, fn).

func (*BetterMux) Mount added in v1.1.0

func (mux *BetterMux) Mount(path string, handler http.Handler)

Mount attaches handler to the given path prefix. The prefix is stripped from the request path before it reaches handler (via http.StripPrefix), so a handler mounted at "/static" receives requests rooted at "/".

Both "/static" and "/static/" are accepted and produce the same registration (the subtree pattern "/static/").

func (*BetterMux) Options

func (mux *BetterMux) Options(pattern string, handler http.HandlerFunc)

Options registers handler for the "OPTIONS <pattern>" pattern, using the Go 1.22+ enhanced ServeMux routing.

func (*BetterMux) Patch

func (mux *BetterMux) Patch(pattern string, handler http.HandlerFunc)

Patch registers handler for the "PATCH <pattern>" pattern, using the Go 1.22+ enhanced ServeMux routing.

func (*BetterMux) Post

func (mux *BetterMux) Post(pattern string, handler http.HandlerFunc)

Post registers handler for the "POST <pattern>" pattern, using the Go 1.22+ enhanced ServeMux routing.

func (*BetterMux) Put

func (mux *BetterMux) Put(pattern string, handler http.HandlerFunc)

Put registers handler for the "PUT <pattern>" pattern, using the Go 1.22+ enhanced ServeMux routing.

func (*BetterMux) Route

func (mux *BetterMux) Route(path string, fn func(*BetterMux)) *BetterMux

Route creates a child BetterMux, runs fn on it to register routes, and mounts the child at the given path prefix (see Mount). It returns the child mux so routes can also be registered afterwards.

func (*BetterMux) ServeHTTP

func (mux *BetterMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler by delegating to the underlying http.ServeMux.

func (*BetterMux) With

func (mux *BetterMux) With(mfn func(http.Handler) http.Handler) *BetterMux

With returns a new BetterMux that shares the same underlying http.ServeMux and declares mfn as middleware for it. With can be chained; middleware declared first is applied first (outermost). The middleware chain is applied to a handler when it is registered via Handle, HandleFunc, or any of the method helpers such as Get.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL