package router import ( "net/http" "regexp" "strconv" "strings" ) type closure func(http.ResponseWriter, *http.Request, []string) type route struct { Pattern string Handler closure } //Routes array of route type Routes []route var routes Routes //Add adicionar rota em routes func Add(pattern string, handler closure) { routes = append(routes, route{ pattern, handler, }) } //Match retorna a rota encontrada func Match(w http.ResponseWriter, r *http.Request) { url := r.URL.Path for _, element := range routes { when := element.Pattern pattern := toRegex(when) items := regexSubmatch(pattern, url) if items[0] == url { element.Handler(w, r, items) } } } //PatternURL coloca barra no final de url se não tiver func patternURL(url string) string { lastChar := url[len(url)-1:] if lastChar != "/" { url = url + "/" } return url } //ToRegex converte uma expressao imputada em expressão do go func toRegex(regex string) *regexp.Regexp { return regexp.MustCompile(`(?m)` + regex) } //RegexSubmatch cria os matches aplicando a padrão de regex inputado func regexSubmatch(pattern *regexp.Regexp, str string) []string { data := []string{""} items := pattern.FindAllStringSubmatch(str, -1) if len(items) > 0 { data = items[0] } return data } //ReplaceStringsURL alterar a url imputada colocando as variaveis da url inserida func replaceStringsURL(items []string, urlPattern string) string { for index, element := range items { urlPattern = strings.Replace(urlPattern, "$"+strconv.Itoa(index), element, -1) } return urlPattern }