Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

v0 source pure

v0 - Unaudited: This is an initial version that has not yet been formally audited. A fully audited version will be pu...

Readme View source

v0 - Unaudited This is an initial version of this package that has not yet been formally audited. A fully audited version will be published as a subsequent release. Use in production at your own risk.

mux - Path router for Render

Simple routing and rendering library for Render(path) requests in Gno realms. Similar in spirit to http.ServeMux, with support for path variables ({name}), wildcards (*), and query strings.

Usage

 1package myrealm
 2
 3import "gno.land/p/nt/mux/v0"
 4
 5var router *mux.Router
 6
 7func init() {
 8    router = mux.NewRouter()
 9
10    // Static route.
11    router.HandleFunc("", func(res *mux.ResponseWriter, req *mux.Request) {
12        res.Write("# Home\n")
13    })
14
15    // Named parameter.
16    router.HandleFunc("hello/{name}", func(res *mux.ResponseWriter, req *mux.Request) {
17        name := req.GetVar("name")
18        res.Write("Hello, " + name + "!")
19    })
20
21    // Query string.
22    router.HandleFunc("search", func(res *mux.ResponseWriter, req *mux.Request) {
23        q := req.Query.Get("q")
24        res.Write("Searching for: " + q)
25    })
26
27    // Wildcard - matches the rest of the path.
28    router.HandleFunc("files/*", func(res *mux.ResponseWriter, req *mux.Request) {
29        res.Write("File path: " + req.GetVar("*"))
30    })
31}
32
33// Realm entry point.
34func Render(path string) string {
35    return router.Render(path)
36}

API

 1type Router struct {
 2    NotFoundHandler NotFoundHandler
 3    // unexported
 4}
 5
 6func NewRouter() *Router
 7
 8func (r *Router) HandleFunc(pattern string, fn HandlerFunc)
 9func (r *Router) HandleFuncRlm(pattern string, fn HandlerFuncRlm) // rlm-aware handler
10func (r *Router) HandleErrFunc(pattern string, fn ErrHandlerFunc)
11func (r *Router) SetNotFoundHandler(handler NotFoundHandler)
12func (r *Router) Render(reqPath string) string
13func (r *Router) RenderRlm(_ int, rlm realm, reqPath string) string // dispatches rlm-aware routes
14
15type Request struct {
16    Path        string     // path without query string
17    RawPath     string     // path including "?..." query string
18    HandlerPath string     // pattern that matched this request
19    Query       url.Values // parsed query parameters
20}
21
22func (r *Request) GetVar(key string) string
23
24type ResponseWriter struct{ /* unexported */ }
25
26func (rw *ResponseWriter) Write(data string)
27func (rw *ResponseWriter) Output() string
28
29type Handler struct {
30    Pattern string
31    Fn      HandlerFunc    // set by HandleFunc
32    FnRlm   HandlerFuncRlm // set by HandleFuncRlm
33}
34
35type HandlerFunc     func(*ResponseWriter, *Request)
36type HandlerFuncRlm  func(_ int, rlm realm, res *ResponseWriter, req *Request)
37type ErrHandlerFunc  func(*ResponseWriter, *Request) error
38type NotFoundHandler func(*ResponseWriter, *Request)

Route patterns

  • users - static, matches exactly users.
  • users/{id} - named parameter, extracted with req.GetVar("id").
  • files/* - wildcard, captures all remaining segments. Extract with req.GetVar("*").

Routes are matched in registration order; the first match wins. If no route matches, NotFoundHandler runs (default writes "404").

Notes

  • HandleErrFunc wraps an error-returning handler: a non-nil error is written as "Error: " + err.Error() to the response.
  • Query strings are parsed off reqPath (?foo=bar); access via req.Query (a net/url.Values).
  • req.RawPath keeps the original path including the query string; req.Path strips it.
  • req.GetVar(...) and req.Query.Get(...) return attacker-controlled path/query input. Wrap it with sanitize.InlineText from gno.land/p/nt/markdown/sanitize/v0 before writing it into the response, or user input can inject Markdown structure.
  • Register realm-aware handlers with HandleFuncRlm and dispatch them with RenderRlm(0, cur, path). The plain Render path only invokes non-rlm Fn handlers.

Overview

v0 - Unaudited: This is an initial version that has not yet been formally audited. A fully audited version will be published as a subsequent release. Use in production at your own risk.

Package mux provides a simple routing and rendering library for handling dynamic path-based requests in Gno contracts.

The `mux` package aims to offer similar functionality to `http.ServeMux` in Go, but for Gno's Render() requests. It allows you to define routes with dynamic parts and associate them with corresponding handler functions for rendering outputs.

Usage: 1. Create a new Router instance using `NewRouter()` to handle routing and rendering logic. 2. Register routes and their associated handler functions using the `Handle(route, handler)` method. 3. Implement the rendering logic within the handler functions, utilizing the `Request` and `ResponseWriter` types. 4. Use the `Render(path)` method to process a given path and execute the corresponding handler function to obtain the rendered output.

Route Patterns: Routes can include dynamic parts enclosed in braces, such as "users/{id}" or "hello/{name}". The `Request` object's `GetVar(key)` method allows you to extract the value of a specific variable from the path based on routing rules.

Example:

Example
 1router := mux.NewRouter()
 2
 3// Define a route with a variable and associated handler function
 4router.HandleFunc("hello/{name}", func(res *mux.ResponseWriter, req *mux.Request) {
 5	name := req.GetVar("name")
 6	if name != "" {
 7		res.Write("Hello, " + name + "!")
 8	} else {
 9		res.Write("Hello, world!")
10	}
11})
12
13// Render the output for the "/hello/Alice" path
14output := router.Render("hello/Alice")
15// Output: "Hello, Alice!"

Note: The `mux` package provides a basic routing and rendering mechanism for simple use cases. For more advanced routing features, consider using more specialized libraries or frameworks.

Functions 1

func NewRouter

1func NewRouter() *Router
source

NewRouter creates a new Router instance.

Types 8

type Handler

struct
1type Handler struct {
2	Pattern string
3	Fn      HandlerFunc
4	FnRlm   HandlerFuncRlm
5}
source

Handler stores a route pattern with one of two handler shapes. Fn (HandlerFunc, no rlm) is set by HandleFunc; FnRlm (HandlerFuncRlm, rlm-aware non-crossing) is set by HandleFuncRlm. Exactly one is set per route. RenderRlm dispatches FnRlm with the supplied rlm; Render dispatches Fn and panics if the matched route was registered with HandleFuncRlm (caller used the wrong dispatch method).

type HandlerFuncRlm

func
1type HandlerFuncRlm func(_ int, rlm realm, res *ResponseWriter, req *Request)
source

HandlerFuncRlm is the rlm-aware handler shape — non-crossing (`_ int, rlm realm` first params) so callers thread cur as data for the handler to forward to downstream crossing functions.

type Request

struct
 1type Request struct {
 2	// Path is request path name.
 3	//
 4	// Note: use RawPath to obtain a raw path with query string.
 5	Path string
 6
 7	// RawPath contains a whole request path, including query string.
 8	RawPath string
 9
10	// HandlerPath is handler rule that matches a request.
11	HandlerPath string
12
13	// Query contains the parsed URL query parameters.
14	Query url.Values
15}
source

Request represents an incoming request.

Methods on Request

func GetVar

method on Request
1func (r *Request) GetVar(key string) string
source

GetVar retrieves a variable from the path based on routing rules.

type ResponseWriter

struct
1type ResponseWriter struct {
2	output strings.Builder
3}
source

ResponseWriter represents the response writer.

Methods on ResponseWriter

func Output

method on ResponseWriter
1func (rw *ResponseWriter) Output() string
source

Output returns the final response output.

func Write

method on ResponseWriter
1func (rw *ResponseWriter) Write(data string)
source

Write appends data to the response output.

type Router

struct
1type Router struct {
2	routes          []Handler
3	NotFoundHandler NotFoundHandler
4}
source

Router handles the routing and rendering logic.

Methods on Router

func HandleErrFunc

method on Router
1func (r *Router) HandleErrFunc(pattern string, fn ErrHandlerFunc)
source

HandleErrFunc registers a route and its error handler function.

func HandleFunc

method on Router
1func (r *Router) HandleFunc(pattern string, fn HandlerFunc)
source

HandleFunc registers a route and its handler function.

func HandleFuncRlm

method on Router
1func (r *Router) HandleFuncRlm(pattern string, fn HandlerFuncRlm)
source

HandleFuncRlm registers a route with a rlm-aware handler. Dispatch must use Router.RenderRlm — calling Router.Render on a route registered via HandleFuncRlm panics (no rlm to supply).

func Render

method on Router
1func (r *Router) Render(reqPath string) string
source

Render renders the output for the given path using the registered route handler.

func RenderRlm

method on Router
1func (r *Router) RenderRlm(_ int, rlm realm, reqPath string) string
source

RenderRlm is the rlm-aware counterpart of Render. Dispatches matched routes registered via HandleFuncRlm with the supplied rlm; routes registered via the legacy HandleFunc still work — rlm is ignored. Use this when the router carries any rlm-aware handlers.

func SetNotFoundHandler

method on Router
1func (r *Router) SetNotFoundHandler(handler NotFoundHandler)
source

SetNotFoundHandler sets custom message for 404 defaultNotFoundHandler.

Imports 2

  • net/url stdlib
  • strings stdlib

Source Files 10