Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Playground

doc.gno

// 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:
//
//	router := mux.NewRouter()
//
//	// Define a route with a variable and associated handler function
//	router.HandleFunc("hello/{name}", func(res *mux.ResponseWriter, req *mux.Request) {
//		name := req.GetVar("name")
//		if name != "" {
//			res.Write("Hello, " + name + "!")
//		} else {
//			res.Write("Hello, world!")
//		}
//	})
//
//	// Render the output for the "/hello/Alice" path
//	output := router.Render("hello/Alice")
//	// 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.
package mux

gnomod.toml

module = "gno.land/p/nt/mux/v0"
gno = "0.9"

[addpkg]
  creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"

handler.gno

package mux

// 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 Handler struct {
	Pattern string
	Fn      HandlerFunc
	FnRlm   HandlerFuncRlm
}

type HandlerFunc func(*ResponseWriter, *Request)

// 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 HandlerFuncRlm func(_ int, rlm realm, res *ResponseWriter, req *Request)

type ErrHandlerFunc func(*ResponseWriter, *Request) error

type NotFoundHandler func(*ResponseWriter, *Request)

// TODO: AutomaticIndex

helpers.gno

package mux

func defaultNotFoundHandler(res *ResponseWriter, req *Request) {
	res.Write("404")
}

request.gno

package mux

import (
	"net/url"
	"strings"
)

// Request represents an incoming request.
type Request struct {
	// Path is request path name.
	//
	// Note: use RawPath to obtain a raw path with query string.
	Path string

	// RawPath contains a whole request path, including query string.
	RawPath string

	// HandlerPath is handler rule that matches a request.
	HandlerPath string

	// Query contains the parsed URL query parameters.
	Query url.Values
}

// GetVar retrieves a variable from the path based on routing rules.
func (r *Request) GetVar(key string) string {
	handlerParts := strings.Split(r.HandlerPath, "/")
	reqParts := strings.Split(r.Path, "/")
	reqIndex := 0
	for handlerIndex := 0; handlerIndex < len(handlerParts); handlerIndex++ {
		handlerPart := handlerParts[handlerIndex]
		switch {
		case handlerPart == "*":
			// If a wildcard "*" is found, consume all remaining segments
			wildcardParts := reqParts[reqIndex:]
			reqIndex = len(reqParts)                // Consume all remaining segments
			return strings.Join(wildcardParts, "/") // Return all remaining segments as a string
		case strings.HasPrefix(handlerPart, "{") && strings.HasSuffix(handlerPart, "}"):
			// If a variable of the form {param} is found we compare it with the key
			parameter := handlerPart[1 : len(handlerPart)-1]
			if parameter == key {
				return reqParts[reqIndex]
			}
			reqIndex++
		default:
			if reqIndex >= len(reqParts) || handlerPart != reqParts[reqIndex] {
				return ""
			}
			reqIndex++
		}
	}

	return ""
}

request_test.gno

package mux

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
	"gno.land/p/nt/ufmt/v0"
)

func TestRequest_GetVar(t *testing.T) {
	cases := []struct {
		handlerPath    string
		reqPath        string
		getVarKey      string
		expectedOutput string
	}{

		{"users/{id}", "users/123", "id", "123"},
		{"users/123", "users/123", "id", ""},
		{"users/{id}", "users/123", "nonexistent", ""},
		{"users/{userId}/posts/{postId}", "users/123/posts/456", "userId", "123"},
		{"users/{userId}/posts/{postId}", "users/123/posts/456", "postId", "456"},

		// Wildcards
		{"*", "users/123", "*", "users/123"},
		{"*", "users/123/posts/456", "*", "users/123/posts/456"},
		{"*", "users/123/posts/456/comments/789", "*", "users/123/posts/456/comments/789"},
		{"users/*", "users/john/posts", "*", "john/posts"},
		{"users/*/comments", "users/jane/comments", "*", "jane/comments"},
		{"api/*/posts/*", "api/v1/posts/123", "*", "v1/posts/123"},

		// wildcards and parameters
		{"api/{version}/*", "api/v1/user/settings", "version", "v1"},
	}
	for _, tt := range cases {
		name := ufmt.Sprintf("%s-%s", tt.handlerPath, tt.reqPath)
		t.Run(name, func(t *testing.T) {
			req := &Request{
				HandlerPath: tt.handlerPath,
				Path:        tt.reqPath,
			}
			output := req.GetVar(tt.getVarKey)
			uassert.Equal(t, tt.expectedOutput, output,
				"handler: %q, path: %q, key: %q",
				tt.handlerPath, tt.reqPath, tt.getVarKey)
		})
	}
}

response.gno

package mux

import "strings"

// ResponseWriter represents the response writer.
type ResponseWriter struct {
	output strings.Builder
}

// Write appends data to the response output.
func (rw *ResponseWriter) Write(data string) {
	rw.output.WriteString(data)
}

// Output returns the final response output.
func (rw *ResponseWriter) Output() string {
	return rw.output.String()
}

// TODO: func (rw *ResponseWriter) Header()...

router.gno

package mux

import (
	"net/url"
	"strings"
)

// Router handles the routing and rendering logic.
type Router struct {
	routes          []Handler
	NotFoundHandler NotFoundHandler
}

// NewRouter creates a new Router instance.
func NewRouter() *Router {
	return &Router{
		routes:          make([]Handler, 0),
		NotFoundHandler: defaultNotFoundHandler,
	}
}

// Render renders the output for the given path using the registered route handler.
func (r *Router) Render(reqPath string) string {
	clearPath, rawQuery, _ := strings.Cut(reqPath, "?")
	query, _ := url.ParseQuery(rawQuery)
	reqParts := strings.Split(clearPath, "/")

	for _, route := range r.routes {
		patParts := strings.Split(route.Pattern, "/")
		wildcard := false
		for _, part := range patParts {
			if part == "*" {
				wildcard = true
				break
			}
		}
		if !wildcard && len(patParts) != len(reqParts) {
			continue
		}

		match := true
		for i := 0; i < len(patParts); i++ {
			patPart := patParts[i]
			reqPart := reqParts[i]

			if patPart == "*" {
				break
			}
			if strings.HasPrefix(patPart, "{") && strings.HasSuffix(patPart, "}") {
				continue
			}
			if patPart != reqPart {
				match = false
				break
			}
		}
		if match {
			req := &Request{
				Path:        clearPath,
				RawPath:     reqPath,
				HandlerPath: route.Pattern,
				Query:       query,
			}
			res := &ResponseWriter{}
			if route.Fn == nil {
				panic("Router.Render: route " + route.Pattern + " was registered via HandleFuncRlm; use RenderRlm to dispatch")
			}
			route.Fn(res, req)
			return res.Output()
		}
	}

	// not found
	req := &Request{Path: reqPath, Query: query}
	res := &ResponseWriter{}
	r.NotFoundHandler(res, req)
	return res.Output()
}

// 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 (r *Router) RenderRlm(_ int, rlm realm, reqPath string) string {
	clearPath, rawQuery, _ := strings.Cut(reqPath, "?")
	query, _ := url.ParseQuery(rawQuery)
	reqParts := strings.Split(clearPath, "/")

	for _, route := range r.routes {
		patParts := strings.Split(route.Pattern, "/")
		wildcard := false
		for _, part := range patParts {
			if part == "*" {
				wildcard = true
				break
			}
		}
		if !wildcard && len(patParts) != len(reqParts) {
			continue
		}

		match := true
		for i := 0; i < len(patParts); i++ {
			patPart := patParts[i]
			reqPart := reqParts[i]

			if patPart == "*" {
				break
			}
			if strings.HasPrefix(patPart, "{") && strings.HasSuffix(patPart, "}") {
				continue
			}
			if patPart != reqPart {
				match = false
				break
			}
		}
		if match {
			req := &Request{
				Path:        clearPath,
				RawPath:     reqPath,
				HandlerPath: route.Pattern,
				Query:       query,
			}
			res := &ResponseWriter{}
			if route.FnRlm != nil {
				route.FnRlm(0, rlm, res, req)
			} else {
				route.Fn(res, req)
			}
			return res.Output()
		}
	}

	// not found
	req := &Request{Path: reqPath, Query: query}
	res := &ResponseWriter{}
	r.NotFoundHandler(res, req)
	return res.Output()
}

// HandleFunc registers a route and its handler function.
func (r *Router) HandleFunc(pattern string, fn HandlerFunc) {
	route := Handler{Pattern: pattern, Fn: fn}
	r.routes = append(r.routes, route)
}

// 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 (r *Router) HandleFuncRlm(pattern string, fn HandlerFuncRlm) {
	route := Handler{Pattern: pattern, FnRlm: fn}
	r.routes = append(r.routes, route)
}

// HandleErrFunc registers a route and its error handler function.
func (r *Router) HandleErrFunc(pattern string, fn ErrHandlerFunc) {
	// Convert ErrHandlerFunc to regular HandlerFunc
	handler := func(res *ResponseWriter, req *Request) {
		if err := fn(res, req); err != nil {
			res.Write("Error: " + err.Error())
		}
	}

	r.HandleFunc(pattern, handler)
}

// SetNotFoundHandler sets custom message for 404 defaultNotFoundHandler.
func (r *Router) SetNotFoundHandler(handler NotFoundHandler) {
	r.NotFoundHandler = handler
}

router_test.gno

package mux

import (
	"testing"

	"gno.land/p/nt/uassert/v0"
)

func TestRouter_Render(t *testing.T) {
	cases := []struct {
		label          string
		path           string
		expectedOutput string
		setupHandler   func(t *testing.T, r *Router)
	}{
		{
			label:          "route with named parameter",
			path:           "hello/Alice",
			expectedOutput: "Hello, Alice!",
			setupHandler: func(t *testing.T, r *Router) {
				r.HandleFunc("hello/{name}", func(rw *ResponseWriter, req *Request) {
					name := req.GetVar("name")
					uassert.Equal(t, "Alice", name)
					rw.Write("Hello, " + name + "!")
				})
			},
		},
		{
			label:          "static route",
			path:           "hi",
			expectedOutput: "Hi, earth!",
			setupHandler: func(t *testing.T, r *Router) {
				r.HandleFunc("hi", func(rw *ResponseWriter, req *Request) {
					uassert.Equal(t, req.Path, "hi")
					rw.Write("Hi, earth!")
				})
			},
		},
		{
			label:          "route with named parameter and query string",
			path:           "hello/foo/bar?foo=bar&baz",
			expectedOutput: "foo bar",
			setupHandler: func(t *testing.T, r *Router) {
				r.HandleFunc("hello/{key}/{val}", func(rw *ResponseWriter, req *Request) {
					key := req.GetVar("key")
					val := req.GetVar("val")
					uassert.Equal(t, "foo", key)
					uassert.Equal(t, "bar", val)
					uassert.Equal(t, "hello/foo/bar?foo=bar&baz", req.RawPath)
					uassert.Equal(t, "hello/foo/bar", req.Path)
					uassert.Equal(t, "bar", req.Query.Get("foo"))
					uassert.Empty(t, req.Query.Get("baz"))
					rw.Write(key + " " + val)
				})
			},
		},
		{
			// TODO: finalize how router should behave with double slash in path.
			label:          "double slash in nested route",
			path:           "a/foo//",
			expectedOutput: "test foo",
			setupHandler: func(t *testing.T, r *Router) {
				r.HandleFunc("a/{key}", func(rw *ResponseWriter, req *Request) {
					// Assert not called
					uassert.False(t, true, "unexpected handler called")
				})

				r.HandleFunc("a/{key}/{val}/", func(rw *ResponseWriter, req *Request) {
					key := req.GetVar("key")
					val := req.GetVar("val")
					uassert.Equal(t, key, "foo")
					uassert.Empty(t, val)
					rw.Write("test " + key)
				})
			},
		},
		{
			label:          "wildcard in route",
			path:           "hello/Alice/Bob",
			expectedOutput: "Matched: Alice/Bob",
			setupHandler: func(t *testing.T, r *Router) {
				r.HandleFunc("hello/*", func(rw *ResponseWriter, req *Request) {
					path := req.GetVar("*")
					uassert.Equal(t, "Alice/Bob", path)
					uassert.Equal(t, "hello/Alice/Bob", req.Path)
					rw.Write("Matched: " + path)
				})
			},
		},
		{
			label:          "wildcard in route with query string",
			path:           "hello/Alice/Bob?foo=bar",
			expectedOutput: "Matched: Alice/Bob",
			setupHandler: func(t *testing.T, r *Router) {
				r.HandleFunc("hello/*", func(rw *ResponseWriter, req *Request) {
					path := req.GetVar("*")
					uassert.Equal(t, "Alice/Bob", path)
					uassert.Equal(t, "hello/Alice/Bob?foo=bar", req.RawPath)
					uassert.Equal(t, "hello/Alice/Bob", req.Path)
					uassert.Equal(t, "bar", req.Query.Get("foo"))
					rw.Write("Matched: " + path)
				})
			},
		},
		// TODO: {"hello", "Hello, world!"},
		// TODO: hello/, /hello, hello//Alice, hello/Alice/, hello/Alice/Bob, etc
	}
	for _, tt := range cases {
		t.Run(tt.label, func(t *testing.T) {
			router := NewRouter()
			tt.setupHandler(t, router)
			output := router.Render(tt.path)
			if output != tt.expectedOutput {
				t.Errorf("Expected output %q, but got %q", tt.expectedOutput, output)
			}
		})
	}
}