github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/examples/gno.land/p/demo/mux/doc.gno (about)

     1  // Package mux provides a simple routing and rendering library for handling dynamic path-based requests in Gno contracts.
     2  //
     3  // The `mux` package aims to offer similar functionality to `http.ServeMux` in Go, but for Gno's Render() requests.
     4  // It allows you to define routes with dynamic parts and associate them with corresponding handler functions for rendering outputs.
     5  //
     6  // Usage:
     7  // 1. Create a new Router instance using `NewRouter()` to handle routing and rendering logic.
     8  // 2. Register routes and their associated handler functions using the `Handle(route, handler)` method.
     9  // 3. Implement the rendering logic within the handler functions, utilizing the `Request` and `ResponseWriter` types.
    10  // 4. Use the `Render(path)` method to process a given path and execute the corresponding handler function to obtain the rendered output.
    11  //
    12  // Route Patterns:
    13  // Routes can include dynamic parts enclosed in braces, such as "users/{id}" or "hello/{name}". The `Request` object's `GetVar(key)`
    14  // method allows you to extract the value of a specific variable from the path based on routing rules.
    15  //
    16  // Example:
    17  //
    18  //	router := mux.NewRouter()
    19  //
    20  //	// Define a route with a variable and associated handler function
    21  //	router.HandleFunc("hello/{name}", func(res *mux.ResponseWriter, req *mux.Request) {
    22  //		name := req.GetVar("name")
    23  //		if name != "" {
    24  //			res.Write("Hello, " + name + "!")
    25  //		} else {
    26  //			res.Write("Hello, world!")
    27  //		}
    28  //	})
    29  //
    30  //	// Render the output for the "/hello/Alice" path
    31  //	output := router.Render("hello/Alice")
    32  //	// Output: "Hello, Alice!"
    33  //
    34  // Note: The `mux` package provides a basic routing and rendering mechanism for simple use cases. For more advanced routing features,
    35  // consider using more specialized libraries or frameworks.
    36  package mux