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.
http.Error(w, err.Error(), 500).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)
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.