Ivy offers a streamlined solution for building web applications using a net/http based router that features an intuitive fiber-like API. With support for sub-routers, middleware, and request-level data passing, it simplifies the process of handling HTTP methods while providing built-in error management.
Ivy is a robust HTTP router built upon the net/http package, offering a fiber-like API for streamlined web application development. This project is designed for developers seeking an efficient and flexible routing solution for their applications.
Key Features
- Standard HTTP Methods: Easily create routes using standard HTTP methods, making route definition simpler and more intuitive.
- Error Handling: Manage errors more effectively by allowing handlers to return errors that can be processed globally, rather than repetitive error responses throughout handlers using
http.Error(w, err.Error(), 500)
. - SubRouters: Create sub-router structures and seamlessly mount them into parent routers, enhancing code organization and modularity.
- Simplified HTTP Responses: Utilize simpler abstractions to write HTTP responses, improving the ease of response handling.
- Middleware Support: Incorporate middleware functions to customize and enhance the HTTP request lifecycle.
- Request-Level Key-Value Store: Pass data between middleware and handlers using a dedicated key-value store, facilitating smoother data management within the request lifecycle.
Usage Example
Below is a sample code demonstrating how to use Ivy for creating a new router and defining routes with middleware support:
router := ivy.NewRouter(
// Optional custom error handler
ivy.WithErrorHandler(func(err error, w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("[ERROR HANDLER]: %s", err.Error()), 500)
}),
)
// Define middleware
router.Use(func (c *ivy.Context) error {
return c.Next()
})
// Set up routes
router.Get("/ping", func(c *ivy.Context) error {
return c.SendString("OK ! from router 1")
})
// Create and mount a sub-router
router2 := ivy.NewRouter()
router2.Get("/_ping",
func(c *ivy.Context) error {
logger.Info("INSIDE middleware 1")
c.KV.Set("hello", "world")
return c.Next()
},
func(c *ivy.Context) error {
logger.Info("INSIDE middleware 2")
return c.Next()
},
func(c *ivy.Context) error {
return c.SendString(fmt.Sprintf("OK! from router 2 (hello = %v)", c.KV.Get("hello")))
},
)
// Mount the sub-router
router.Mount("/v2", router2)
// Start the server
http.ListenAndServe(":8080", router)
Additional Examples
To further explore routing capabilities, see the Sub Router Example.
Ivy simplifies HTTP routing, making it an excellent choice for developers looking for a clean and efficient routing framework.
No comments yet.
Sign in to be the first to comment.