Routing

Routing will bridge the requested path and Controller.
Basically, route and Controller are paired, so never run any Controller if routing is not defined.

Route definition

You can define routing in config/routes.go.

package config

import (
    "github.com/naoina/kocha"
    "your/app/controller"
)

type RouteTable kocha.RouteTable

var routes = RouteTable{
    {
        Name:       "root",
        Path:       "/",
        Controller: &controller.Root{},
    },
}

func Routes() RouteTable {
    return append(routes, RouteTable{
        {
            Name:       "static",
            Path:       "/*path",
            Controller: &kocha.StaticServe{},
        },
    }...)
}

format:

{
    Name:       "root",
    Path:       "/",
    Controller: &controller.Root{},
}

Name field is name of route. it use for reverse routing. (url function in template, Reverse in Go code)
Path field is routing path. Kocha will be routed to Controller when request path matches Path.
For example, If route is defined the following:

{
    Name:       "myroom"
    Path:       "/myroom"
    Controller: &controller.Myroom{},
}

And when request is GET /myroom, it will be routed to controller.Myroom.GET method.
Also when request is POST /myroom, it will be routed to controller.Myroom.POST method.

Route parameter

Routing path can specify parameters.
They parameters will be validated in boot time.

Route parameter must be started with ":" or "*". Normally, use ":" except you want to get the path parameter.

For example:

Path: "/:name"

This is routing definition that it includes :name route parameter.
If Controller.GET of that route is defined as follows:

func (r *Root) GET(c *kocha.Context) error {
    c.Params.Get("name")
    ......
}

:name route parameter matches any string. (but "/" is not included)
For example, it will match /alice, but won't match /alice/1.
Then matched value (alice in this example) will be stored to Context.Params as name key.

Also multiple parameters can be specified.
For example,

Route:

Path: "/:id/:name"

Controller:

func (r *Root) GET(c *kocha.Context) error {
    c.Params.Get("id")
    c.Params.Get("name")
    ......
}

Above example matches all of /1/alice, /10/alice, /2/bob, /str/alice and etc.

Path parameter

When route parameter starts with "*", it will match all word characters.

For example,

Route:

Path: "/*path"

Controller:

func (r *Root) GET(c *kocha.Context) error {
    c.Params.Get("path")
    ......
}

If GET /path/to/static.png requests to the above example, Context.Params.Get will return "path/to/static.png".