mux

package module
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2025 License: MIT Imports: 15 Imported by: 0

README

Mux - A Lightweight HTTP Router for Go

Mux is a simple, lightweight HTTP router for Go that wraps around the standard http.ServeMux to provide additional functionality and a more ergonomic API.

Features

  • HTTP method-specific routing (GET, POST, PUT, DELETE, etc.)
  • Middleware support with flexible stacking
  • Route grouping for organization and shared middleware
  • RESTful resource routing
  • URL parameter extraction
  • Graceful shutdown support
  • Minimal dependencies (only uses Go standard library)

Installation

go get code.patial.tech/go/mux

Basic Usage

package main

import (
	"fmt"
	"net/http"

	"code.patial.tech/go/mux"
)

func main() {
	// Create a new router
	router := mux.NewRouter()

	// Define a simple route
	router.GET("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "Hello, World!")
	})

	// Start the server
	http.ListenAndServe(":8080", router)
}

Routing

Mux supports all HTTP methods defined in the Go standard library:

router.GET("/users", listUsers)
router.POST("/users", createUser)
router.PUT("/users/{id}", updateUser)
router.DELETE("/users/{id}", deleteUser)
router.PATCH("/users/{id}", partialUpdateUser)
router.HEAD("/users", headUsers)
router.OPTIONS("/users", optionsUsers)
router.TRACE("/users", traceUsers)
router.CONNECT("/users", connectUsers)

URL Parameters

Mux supports URL parameters using curly braces:

router.GET("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
	fmt.Fprintf(w, "User ID: %s", id)
})

Middleware

Middleware functions take an http.Handler and return an http.Handler. You can add global middleware to all routes:

// Logging middleware
func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Printf("[%s] %s\n", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}

// Add middleware to all routes
router.Use(loggingMiddleware)

Route Groups

Group related routes and apply middleware to specific groups:

// API routes group
router.Group(func(api *mux.Router) {
	// Middleware only for API routes
	api.Use(authMiddleware)

	// API routes
	api.GET("/api/users", listUsers)
	api.POST("/api/users", createUser)
})

RESTful Resources

Easily define RESTful resources:

router.Resource("/posts", func(r *mux.Resource) {
	r.Index(listPosts)    // GET /posts
	r.Show(showPost)      // GET /posts/{id}
	r.Create(createPost)  // POST /posts
	r.Update(updatePost)  // PUT /posts/{id}
	r.Destroy(deletePost) // DELETE /posts/{id}
	r.New(newPostForm)    // GET /posts/new
})

Graceful Shutdown

Use the built-in graceful shutdown functionality:

router.Serve(func(srv *http.Server) error {
	srv.Addr = ":8080"
	return srv.ListenAndServe()
})

Custom 404 Handler

can be tried like this

router.GET("/", func(writer http.ResponseWriter, request *http.Request) {
    if request.URL.Path != "/" {
        writer.WriteHeader(404)
        writer.Write([]byte(`not found, da xiong dei !!!`))
        return
    }
})

Full Example

See the examples directory for complete working examples.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Mux added in v0.5.0

type Mux struct {
	IsShuttingDown atomic.Bool
	// contains filtered or unexported fields
}

Mux is a wrapper around the go's standard http.ServeMux. It's a lean wrapper with methods to make routing easier

func New added in v0.5.0

func New() *Mux

func (*Mux) CONNECT added in v0.5.0

func (m *Mux) CONNECT(pattern string, h http.HandlerFunc)

CONNECT method route

func (*Mux) DELETE added in v0.5.0

func (m *Mux) DELETE(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler)

DELETE method route

func (*Mux) GET added in v0.5.0

func (m *Mux) GET(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler)

GET method route

func (*Mux) Group added in v0.5.0

func (m *Mux) Group(fn func(grp *Mux))

Group adds a new inline-Router along the current routing path, with a fresh middleware stack for the inline-Router.

func (*Mux) HEAD added in v0.5.0

func (m *Mux) HEAD(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler)

HEAD method route

func (*Mux) HttpServeMux added in v0.5.0

func (m *Mux) HttpServeMux() *http.ServeMux

HttpServeMux DO NOT USE it for routing, exposed only for edge cases.

func (*Mux) OPTIONS added in v0.5.0

func (m *Mux) OPTIONS(pattern string, h http.HandlerFunc)

OPTIONS method route

func (*Mux) PATCH added in v0.5.0

func (m *Mux) PATCH(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler)

PATCH method route

func (*Mux) POST added in v0.5.0

func (m *Mux) POST(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler)

POST method route

func (*Mux) PUT added in v0.5.0

func (m *Mux) PUT(pattern string, h http.HandlerFunc, mw ...func(http.Handler) http.Handler)

PUT method route

func (*Mux) PrintRoutes added in v0.5.0

func (m *Mux) PrintRoutes(w io.Writer)

func (*Mux) Resource added in v0.5.0

func (m *Mux) Resource(pattern string, fn func(res *Resource), mw ...func(http.Handler) http.Handler)

Resource routes mapping by using HTTP verbs

  • GET /pattern view all resources
  • GET /pattern/create new resource view
  • POST /pattern create a new resource
  • GET /pattern/:id view a resource
  • PUT /pattern/:id update a resource
  • PATCH /pattern/:id partial update a resource
  • DELETE /resource/:id delete a resource

func (*Mux) RouteList added in v0.5.0

func (m *Mux) RouteList() []string

func (*Mux) Serve added in v0.5.0

func (m *Mux) Serve(cb ServeCB)

Serve with graceful shutdown

func (*Mux) ServeHTTP added in v0.5.0

func (m *Mux) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Mux) TRACE added in v0.5.0

func (m *Mux) TRACE(pattern string, h http.HandlerFunc)

TRACE method route

func (*Mux) Use added in v0.5.0

func (m *Mux) Use(h ...func(http.Handler) http.Handler)

Use will register middleware(s) with router stack

func (*Mux) With added in v0.5.0

func (m *Mux) With(mw ...func(http.Handler) http.Handler) *Mux

With adds inline middlewares for an endpoint handler.

type Resource

type Resource struct {
	// contains filtered or unexported fields
}

func (*Resource) Create

func (res *Resource) Create(h http.HandlerFunc)

Create a new resource

POST /pattern/create

func (*Resource) CreateView added in v0.5.0

func (res *Resource) CreateView(h http.HandlerFunc)

CreateView new resource

GET /pattern/create

func (*Resource) Delete added in v0.5.0

func (res *Resource) Delete(h http.HandlerFunc)

Delete a resource

DELETE /pattern/:id

func (*Resource) HandleDELETE added in v0.7.1

func (res *Resource) HandleDELETE(pattern string, h http.HandlerFunc)

HandleDELETE on /group-pattern/:id/pattern

func (*Resource) HandleGET added in v0.7.1

func (res *Resource) HandleGET(pattern string, h http.HandlerFunc)

HandleGET on /group-pattern/:id/pattern

func (*Resource) HandlePATCH added in v0.7.1

func (res *Resource) HandlePATCH(pattern string, h http.HandlerFunc)

HandlePATCH on /group-pattern/:id/pattern

func (*Resource) HandlePOST added in v0.7.1

func (res *Resource) HandlePOST(pattern string, h http.HandlerFunc)

HandlePOST on /group-pattern/:id/pattern

func (*Resource) HandlePUT added in v0.7.1

func (res *Resource) HandlePUT(pattern string, h http.HandlerFunc)

HandlePUT on /group-pattern/:id/pattern

func (*Resource) Index

func (res *Resource) Index(h http.HandlerFunc)

Index of all resource.

GET /pattern

func (*Resource) Update

func (res *Resource) Update(h http.HandlerFunc)

Update a resource

PUT /pattern/:id

func (*Resource) UpdatePartial added in v0.5.0

func (res *Resource) UpdatePartial(h http.HandlerFunc)

UpdatePartial resource info PATCH /pattern/:id

func (*Resource) Use

func (res *Resource) Use(middlewares ...func(http.Handler) http.Handler)

Use will register middleware(s) on Router stack.

func (*Resource) View added in v0.5.0

func (res *Resource) View(h http.HandlerFunc)

View a resource

GET /pattern/:id

type RouteList added in v0.5.0

type RouteList struct {
	// contains filtered or unexported fields
}

func (*RouteList) Add added in v0.5.0

func (s *RouteList) Add(item string)

func (*RouteList) All added in v0.5.0

func (s *RouteList) All() []string

func (*RouteList) Get added in v0.5.0

func (s *RouteList) Get(index int) (string, error)

type ServeCB

type ServeCB func(srv *http.Server) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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