mux/README.md

154 lines
3.3 KiB
Markdown
Raw Normal View History

# Mux - A Lightweight HTTP Router for Go
2024-09-30 13:31:11 +00:00
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.
2024-10-12 19:34:17 +05:30
## 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
```bash
go get code.patial.tech/go/mux
```
## Basic Usage
2024-10-12 19:34:17 +05:30
```go
package main
import (
"fmt"
2024-10-12 19:34:17 +05:30
"net/http"
"code.patial.tech/go/mux"
2024-10-12 19:34:17 +05:30
)
func main() {
// Create a new router
router := mux.NewRouter()
2024-10-12 19:34:17 +05:30
// Define a simple route
router.GET("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, World!")
})
2024-10-12 19:40:54 +05:30
// Start the server
http.ListenAndServe(":8080", router)
}
```
2024-10-12 19:34:17 +05:30
## Routing
2024-10-12 19:34:17 +05:30
Mux supports all HTTP methods defined in the Go standard library:
2024-10-12 19:34:17 +05:30
```go
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)
```
2024-10-12 19:34:17 +05:30
## URL Parameters
2024-10-12 19:34:17 +05:30
Mux supports URL parameters using curly braces:
2024-10-12 19:34:17 +05:30
```go
router.GET("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
fmt.Fprintf(w, "User ID: %s", id)
})
```
2024-10-12 19:34:17 +05:30
## Middleware
2024-10-12 19:34:17 +05:30
Middleware functions take an `http.Handler` and return an `http.Handler`. You can add global middleware to all routes:
2024-10-12 19:34:17 +05:30
```go
// Logging middleware
func loggingMiddleware(next http.Handler) http.Handler {
2024-10-12 19:34:17 +05:30
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("[%s] %s\n", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
2024-10-12 19:34:17 +05:30
})
}
// Add middleware to all routes
router.Use(loggingMiddleware)
```
## Route Groups
Group related routes and apply middleware to specific groups:
```go
// 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:
```go
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:
```go
router.Serve(func(srv *http.Server) error {
srv.Addr = ":8080"
return srv.ListenAndServe()
})
2024-10-12 19:34:17 +05:30
```
## Custom 404 Handler
can be tried like this
```go
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](./example) for complete working examples.
## License
This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.