3.3 KiB
3.3 KiB
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.