Introduction
httptreemux is a high-performance, flexible HTTP router based on a tree structure, primarily used for Go language development. The project is inspired by Julien Schmidt’s httprouter, but differs in implementation, particularly with more flexible routing rule design. httptreemux manages routes using a Patricia tree, ensuring high performance while providing a more convenient routing pattern design.
Core Features
The core features of httptreemux include:
-
High-performance routing: The routing mechanism based on the Patricia tree ensures efficient route matching.
-
Flexible routing rules: Supports the use of both wildcards and static tokens within a single path segment, making route design more flexible.
-
Supports multiple routing patterns: Including static paths, wildcard paths, and catch-all paths.
-
Supports context and http.HandlerFunc: Since Go 1.7, httptreemux supports using context and http.HandlerFunc type handlers.
-
Routing groups: Supports creating routing groups with path prefixes for easier management of clustered paths.
-
Special method behavior: By default, if a path does not define a handler for HEAD requests, httptreemux will call the GET handler to handle HEAD requests.
Application Scenarios
-
API services: When building RESTful APIs, the flexible routing rules of httptreemux can help you easily handle various resource operations.
-
Web frameworks: If you are developing your own web framework or need a high-performance routing system, httptreemux is a great choice.
-
Microservices architecture: In environments requiring interaction between multiple independent services, each service can utilize httptreemux for clear interface management.
Project Features
-
High performance: Efficient lookup algorithm based on the Patricia tree ensures quick response for routing.
-
Flexible routing rules: The same path segment can be a fixed value or a dynamic parameter, providing greater design space.
-
Supports Go Modules: Easy to integrate into your Go projects, ensuring stability through version control.
-
Native support for http.HandlerFunc: Can seamlessly integrate into Go’s HTTP ecosystem and utilize context to handle request contexts.
-
Routing Groups: By creating routing groups, you can easily manage related path prefixes.
-
Smart redirection: Automatically handles trailing slashes to maintain URL consistency.
Supported Features
-
Wrapped handlers
-
Middleware (handler wrapping)
-
Tree mode routing rules
-
Routing groups (facilitating application expansion)
-
Custom errors
-
Custom redirection
Reference Code
package main
import ( "fmt"
"net/http"
"github.com/vmihailenco/treemux")
func corsMiddleware(next treemux.HandlerFunc) treemux.HandlerFunc { return func(w http.ResponseWriter, req treemux.Request) error { if origin := req.Header.Get("Origin"); origin != "" { h := w.Header() h.Set("Access-Control-Allow-Origin", origin) h.Set("Access-Control-Allow-Credentials", "true") } return next(w, req) }}
func main() { router := treemux.New() group := router.NewGroup("/api") group.GET("/v1/:id", func(w http.ResponseWriter, req treemux.Request) error { id := req.Param("id") fmt.Fprintf(w, "GET /api/v1/%s", id) fmt.Fprintf(w, "route: %s", req.Route()) return nil }) router.Use(corsMiddleware) http.ListenAndServe(":8080", router)}
Rule Explanation
-
Request paths containing ‘:’ are wildcard paths, corresponding to only one path.
-
Request paths containing ‘*’ are catch-all matches, e.g., images/*path can match images/abc/def but will not match an empty string; if needed, configure /images/.
Routing Priority
-
Static path segments have the highest priority
-
Wildcards have the next priority
-
Then comes the catch-all matches
Application Scenarios
httptreemux is a high-performance HTTP router library for Go language. It is designed for fast and flexible routing, suitable for various application scenarios. Here are some main application scenarios:
-
Web applications and services: httptreemux can serve as the routing layer for web applications, handling HTTP requests and dispatching to the appropriate handlers, suitable for building RESTful APIs, website backends, etc.
-
Microservices architecture: In a microservices architecture, each service typically has its own HTTP API. httptreemux can be used for routing management of these services, providing efficient request routing.
-
API Gateway: As part of an API gateway, httptreemux can route requests from clients to multiple backend services, achieving request aggregation and distribution.
-
Single Page Applications (SPA): For single-page applications, httptreemux can provide static file services and route API requests to the corresponding processing logic.
-
File servers: You can build file servers using the routing capabilities of httptreemux to handle file uploads, downloads, and other requests.
-
Real-time communication services: Combined with WebSocket or other real-time communication protocols, httptreemux can be used to build real-time message push, chat rooms, and other applications.
-
Proxy servers: httptreemux can act as a proxy server, forwarding requests to other servers or services.
-
Middleware integration: httptreemux supports middleware, allowing integration of logging, authentication, CORS handling, rate limiting, circuit breaking, and other middleware to enhance application functionality.
-
Command-line tools (CLI): Although httptreemux is primarily used for web applications, it can also be used to build command-line tools with HTTP interfaces.
-
Testing and simulation: In testing environments, httptreemux can be used to simulate HTTP servers for testing client logic.
The lightweight and high-performance features of httptreemux make it suitable for a variety of scenarios requiring fast and flexible routing processing.
Open Source Address
Follow the official account and reply 20241121 to obtain
You might also like:
[Open Source] Local knowledge base Q&A system supporting any file format or database, can be installed and used offline.
[Open Source] Comprehensive, component-independent, extensible domestic workflow engine
[Open Source] Adopts a no-code design concept, providing “free” form questionnaire capabilities for enterprises, “out of the box” rapid empowerment of business
[Open Source] A distributed microservice architecture upgraded and optimized from a commercial-grade project, refactored business code with Java17 API, while providing support for multiple front-end frameworks
[Open Source] An efficient, easy-to-use, powerful API management platform
Add WeChat to join relevant discussion groups,
Note “microservices” to join the group discussion
Note “low cost” to join the low-cost group discussion
Note “AI” to join the AI big data and data governance group discussion
Note “digital” to join the IoT and digital twin group discussion
Note “security” to join security-related group discussions
Note “automation” to join automation and operation and maintenance group discussions
Note “trial” to apply for product trials
Note “channel” to cooperate on channel information
Note “custom” to customize projects, full source code delivery