|
- // Private function bindings to Router.
- //
- // Note: math/rand is imported here and is used for avoiding naming collisions
- // on URLFor names generated using route names.
-
- package capstan
-
- import (
- "math/rand"
- "os"
- "path/filepath"
- "reflect"
- "strconv"
- "time"
- )
-
- // Housekeeping initialization such as PID file generation (if enabled).
- func (r *Router) init() {
- pidfile := r.app.Config().Server.PIDFile
- if pidfile == "" {
- return
- }
-
- cwd, err := os.Getwd()
- if err != nil {
- r.app.Logger().Warning("unable to read current directory:", err)
- return
- }
- pidfile = filepath.Join(cwd, pidfile)
-
- fp, err := os.OpenFile(pidfile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0644))
- if err != nil {
- r.app.Logger().Warning("PIDFile specified but cannot be written:", err)
- return
- }
- defer fp.Close()
-
- if _, err = fp.Write([]byte(strconv.Itoa(os.Getpid()))); err != nil {
- r.app.Logger().Warning("cannot write PID:", err)
- }
- }
-
- func (r *Router) toRoute(controller Controller) (*Route, *routeProps) {
- props := r.ParseRoute(controller.path())
- route := &Route{
- router: r,
- Prefix: controller.prefix(),
- Path: props.route,
- CapPath: controller.path(),
- BasePath: r.basePath, // TODO: Support CapBasePath.
- MandatoryNoSlash: props.mandatoryNoSlash,
- MandatorySlash: props.mandatorySlash,
- OptionalSlash: props.optionalSlash,
- SlashIsDefault: props.slashIsDefault,
- ParamTypes: props.params,
- Middleware: controller.middleware(),
- Controller: controller,
- Renderer: controller.renderer(),
- AfterResponse: make([]func(Context, error) error, len(r.afterResponse)),
- BeforeResponse: make([]func(Context, *Route) error, len(r.beforeResponse)),
- }
-
- // Set route name based on either the controller, as provided, or the
- // underlying type name (via reflection).
- route.Name = controller.name()
- if route.Name == "" {
- route.Name = reflect.Indirect(reflect.ValueOf(controller)).Type().Name()
- }
-
- name := route.Name
- for _, ok := r.cnames[route.Name]; ok; _, ok = r.cnames[route.Name] {
- d := len(route.Name) - len(name)
- if d == 0 {
- route.Name = route.Name + "1"
- continue
- }
-
- if v, err := strconv.Atoi(route.Name[len(route.Name)-d:]); err == nil {
- route.Name = name + strconv.Itoa(v+1)
- } else {
- rand := rand.New(rand.NewSource(time.Now().Unix()))
- route.Name = route.Name + strconv.Itoa(rand.Int())
- }
- }
-
- copy(route.AfterResponse, r.afterResponse)
- copy(route.BeforeResponse, r.beforeResponse)
-
- return route, props
- }
|