Skip to content

Commit

Permalink
impelement Define
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidCai1111 committed Dec 2, 2016
1 parent e6435d3 commit 259bf6b
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 2 deletions.
File renamed without changes.
1 change: 1 addition & 0 deletions parse_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package routing
80 changes: 78 additions & 2 deletions routing.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package routing

import "regexp"
import (
"fmt"
"regexp"
"strings"
)

// Version is this package's version number.
const Version = "0.0.1"
Expand All @@ -9,7 +13,7 @@ const Version = "0.0.1"
type Node struct {
name string
str string
reg regexp.Regexp
reg *regexp.Regexp
parent *Node
child map[string]*Node
children []*Node
Expand All @@ -19,3 +23,75 @@ type Node struct {
func New() *Node {
return &Node{parent: nil}
}

// Define defines a url
func (n *Node) Define(url string) {
if url[0] != '/' {
panic(fmt.Sprintf("routing: %v should start with '/'\n", url))
}

n.define(strings.Split(url, "/")[1:])
}

func (n *Node) define(frags []string) {
options := parse(frags[0])

nodes := []*Node{}

for _, opt := range options {
node := n.find(opt)

if node == nil {
node = n.attach(opt)
}

nodes = append(nodes, node)
}

if len(frags) == 1 {
return
}

for _, node := range nodes {
node.define(frags[1:])
}
}

func (n *Node) find(opt option) *Node {
if opt.str != "" {
c := n.child[opt.str]

if c.str == opt.str && c.name == opt.name {
return c
}

return nil
}

if opt.name != "" {
for _, c := range n.children {
if c.name == opt.name {
return c
}
}
}

return nil
}

func (n *Node) attach(opt option) *Node {
node := &Node{
name: opt.name,
str: opt.str,
reg: opt.reg,
parent: n,
}

if opt.str != "" {
node.child = map[string]*Node{opt.str: node}
} else {
node.children = []*Node{node}
}

return node
}

0 comments on commit 259bf6b

Please sign in to comment.