github.com/kamilchm/hopper@v0.1.1-0.20150901175627-9ee9e15dce47/search.go (about)

     1  // Searching hops
     2  package main
     3  
     4  import (
     5  	"errors"
     6  	"regexp"
     7  	"strings"
     8  )
     9  
    10  var (
    11  	// ErrHopNotFound is returned when there's no hop for given name
    12  	ErrHopNotFound = errors.New("Can't find hop for given pattern")
    13  )
    14  
    15  // Search hops with matchins names
    16  func (hs *hops) searchHop(pattern string) (*hops, error) {
    17  	fHops := make(hops)
    18  	for name, h := range *hs {
    19  		if match(name, pattern) {
    20  			fHops[name] = h
    21  		}
    22  	}
    23  	if len(fHops) == 0 {
    24  		return nil, ErrHopNotFound
    25  	}
    26  	return &fHops, nil
    27  }
    28  
    29  // Tests if name matches given pattern
    30  func match(name, pattern string) bool {
    31  	if strings.ContainsRune(pattern, '*') {
    32  		rPattern := strings.Replace(pattern, "*", ".*", -1)
    33  		r := regexp.MustCompile("^" + rPattern + "$")
    34  		return r.MatchString(name)
    35  	}
    36  	return name == pattern
    37  }