github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/route.go (about)

     1  package buffalo
     2  
     3  import (
     4  	"fmt"
     5  	"html/template"
     6  	"net/url"
     7  	"sort"
     8  	"strings"
     9  )
    10  
    11  // Routes returns a list of all of the routes defined
    12  // in this application.
    13  func (a *App) Routes() RouteList {
    14  	if a.root != nil {
    15  		return a.root.routes
    16  	}
    17  	return a.routes
    18  }
    19  
    20  func addExtraParamsTo(path string, opts map[string]interface{}) string {
    21  	pendingParams := map[string]string{}
    22  	keys := []string{}
    23  	for k, v := range opts {
    24  		if strings.Contains(path, fmt.Sprintf("%v", v)) {
    25  			continue
    26  		}
    27  
    28  		keys = append(keys, k)
    29  		pendingParams[k] = fmt.Sprintf("%v", v)
    30  	}
    31  
    32  	if len(keys) == 0 {
    33  		return path
    34  	}
    35  
    36  	if !strings.Contains(path, "?") {
    37  		path = path + "?"
    38  	} else {
    39  		if !strings.HasSuffix(path, "?") {
    40  			path = path + "&"
    41  		}
    42  	}
    43  
    44  	sort.Strings(keys)
    45  
    46  	for index, k := range keys {
    47  		format := "%v=%v"
    48  
    49  		if index > 0 {
    50  			format = "&%v=%v"
    51  		}
    52  
    53  		path = path + fmt.Sprintf(format, url.QueryEscape(k), url.QueryEscape(pendingParams[k]))
    54  	}
    55  
    56  	return path
    57  }
    58  
    59  //RouteHelperFunc represents the function that takes the route and the opts and build the path
    60  type RouteHelperFunc func(opts map[string]interface{}) (template.HTML, error)
    61  
    62  // RouteList contains a mapping of the routes defined
    63  // in the application. This listing contains, Method, Path,
    64  // and the name of the Handler defined to process that route.
    65  type RouteList []*RouteInfo
    66  
    67  func (a RouteList) Len() int      { return len(a) }
    68  func (a RouteList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
    69  func (a RouteList) Less(i, j int) bool {
    70  	x := a[i].Path // + a[i].Method
    71  	y := a[j].Path // + a[j].Method
    72  	return x < y
    73  }
    74  
    75  // Lookup search a specific PathName in the RouteList and return the *RouteInfo
    76  func (a RouteList) Lookup(name string) (*RouteInfo, error) {
    77  	for _, ri := range a {
    78  		if ri.PathName == name {
    79  			return ri, nil
    80  		}
    81  	}
    82  	return nil, fmt.Errorf("path name not found")
    83  }