| 1 | package pat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "sort" |
| 6 | |
| 7 | "goji.io/internal" |
| 8 | "goji.io/pattern" |
| 9 | ) |
| 10 | |
| 11 | type match struct { |
| 12 | context.Context |
| 13 | pat *Pattern |
| 14 | matches []string |
| 15 | } |
| 16 | |
| 17 | func (m match) Value(key interface{}) interface{} { |
| 18 | switch key { |
| 19 | case pattern.AllVariables: |
| 20 | var vs map[pattern.Variable]interface{} |
| 21 | if vsi := m.Context.Value(key); vsi == nil { |
| 22 | if len(m.pat.pats) == 0 { |
| 23 | return nil |
| 24 | } |
| 25 | vs = make(map[pattern.Variable]interface{}, len(m.matches)) |
| 26 | } else { |
| 27 | vs = vsi.(map[pattern.Variable]interface{}) |
| 28 | } |
| 29 | |
| 30 | for _, p := range m.pat.pats { |
| 31 | vs[p.name] = m.matches[p.idx] |
| 32 | } |
| 33 | return vs |
| 34 | case internal.Path: |
| 35 | if len(m.matches) == len(m.pat.pats)+1 { |
| 36 | return m.matches[len(m.matches)-1] |
| 37 | } |
| 38 | return "" |
| 39 | } |
| 40 | |
| 41 | if k, ok := key.(pattern.Variable); ok { |
| 42 | i := sort.Search(len(m.pat.pats), func(i int) bool { |
| 43 | return m.pat.pats[i].name >= k |
| 44 | }) |
| 45 | if i < len(m.pat.pats) && m.pat.pats[i].name == k { |
| 46 | return m.matches[m.pat.pats[i].idx] |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | return m.Context.Value(key) |
| 51 | } |