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

     1  package mux
     2  
     3  import "strings"
     4  
     5  // Request represents an incoming request.
     6  type Request struct {
     7  	Path        string
     8  	HandlerPath string
     9  }
    10  
    11  // GetVar retrieves a variable from the path based on routing rules.
    12  func (r *Request) GetVar(key string) string {
    13  	var (
    14  		handlerParts = strings.Split(r.HandlerPath, "/")
    15  		reqParts     = strings.Split(r.Path, "/")
    16  	)
    17  
    18  	for i := 0; i < len(handlerParts); i++ {
    19  		handlerPart := handlerParts[i]
    20  		switch {
    21  		case handlerPart == "*":
    22  			// XXX: implement a/b/*/d/e
    23  			panic("not implemented")
    24  		case strings.HasPrefix(handlerPart, "{") && strings.HasSuffix(handlerPart, "}"):
    25  			parameter := handlerPart[1 : len(handlerPart)-1]
    26  			if parameter == key {
    27  				return reqParts[i]
    28  			}
    29  		default:
    30  			// continue
    31  		}
    32  	}
    33  
    34  	return ""
    35  }