github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/examples/gno.land/p/demo/mux/router.gno (about) 1 package mux 2 3 import "strings" 4 5 // Router handles the routing and rendering logic. 6 type Router struct { 7 routes []Handler 8 NotFoundHandler HandlerFunc 9 } 10 11 // NewRouter creates a new Router instance. 12 func NewRouter() *Router { 13 return &Router{ 14 routes: make([]Handler, 0), 15 NotFoundHandler: defaultNotFoundHandler, 16 } 17 } 18 19 // Render renders the output for the given path using the registered route handler. 20 func (r *Router) Render(reqPath string) string { 21 reqParts := strings.Split(reqPath, "/") 22 23 for _, route := range r.routes { 24 patParts := strings.Split(route.Pattern, "/") 25 26 if len(patParts) != len(reqParts) { 27 continue 28 } 29 30 match := true 31 for i := 0; i < len(patParts); i++ { 32 patPart := patParts[i] 33 reqPart := reqParts[i] 34 35 if patPart == "*" { 36 continue 37 } 38 if strings.HasPrefix(patPart, "{") && strings.HasSuffix(patPart, "}") { 39 continue 40 } 41 if patPart != reqPart { 42 match = false 43 break 44 } 45 } 46 if match { 47 req := &Request{ 48 Path: reqPath, 49 HandlerPath: route.Pattern, 50 } 51 res := &ResponseWriter{} 52 route.Fn(res, req) 53 return res.Output() 54 } 55 } 56 57 // not found 58 req := &Request{Path: reqPath} 59 res := &ResponseWriter{} 60 r.NotFoundHandler(res, req) 61 return res.Output() 62 } 63 64 // Handle registers a route and its handler function. 65 func (r *Router) HandleFunc(pattern string, fn HandlerFunc) { 66 route := Handler{Pattern: pattern, Fn: fn} 67 r.routes = append(r.routes, route) 68 }