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

request.gno

1.49 Kb · 54 lines
 1package mux
 2
 3import (
 4	"net/url"
 5	"strings"
 6)
 7
 8// Request represents an incoming request.
 9type Request struct {
10	// Path is request path name.
11	//
12	// Note: use RawPath to obtain a raw path with query string.
13	Path string
14
15	// RawPath contains a whole request path, including query string.
16	RawPath string
17
18	// HandlerPath is handler rule that matches a request.
19	HandlerPath string
20
21	// Query contains the parsed URL query parameters.
22	Query url.Values
23}
24
25// GetVar retrieves a variable from the path based on routing rules.
26func (r *Request) GetVar(key string) string {
27	handlerParts := strings.Split(r.HandlerPath, "/")
28	reqParts := strings.Split(r.Path, "/")
29	reqIndex := 0
30	for handlerIndex := 0; handlerIndex < len(handlerParts); handlerIndex++ {
31		handlerPart := handlerParts[handlerIndex]
32		switch {
33		case handlerPart == "*":
34			// If a wildcard "*" is found, consume all remaining segments
35			wildcardParts := reqParts[reqIndex:]
36			reqIndex = len(reqParts)                // Consume all remaining segments
37			return strings.Join(wildcardParts, "/") // Return all remaining segments as a string
38		case strings.HasPrefix(handlerPart, "{") && strings.HasSuffix(handlerPart, "}"):
39			// If a variable of the form {param} is found we compare it with the key
40			parameter := handlerPart[1 : len(handlerPart)-1]
41			if parameter == key {
42				return reqParts[reqIndex]
43			}
44			reqIndex++
45		default:
46			if reqIndex >= len(reqParts) || handlerPart != reqParts[reqIndex] {
47				return ""
48			}
49			reqIndex++
50		}
51	}
52
53	return ""
54}