Common isomorphic functionality in one kit.

route.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // The Isomorphic Go Project
  2. // Copyright (c) Wirecog, LLC. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license, which can be found in the LICENSE file.
  5. package isokit
  6. import (
  7. "context"
  8. "regexp"
  9. "strings"
  10. )
  11. const (
  12. RouteWithParamsPattern = `/([^/]*)`
  13. RouteOnlyPrefixPattern = `/`
  14. RouteSuffixPattern = `/?$`
  15. )
  16. type Handler interface {
  17. ServeRoute(context.Context)
  18. }
  19. type HandlerFunc func(context.Context)
  20. func (f HandlerFunc) ServeRoute(ctx context.Context) {
  21. f(ctx)
  22. }
  23. type RouteVarsKey string
  24. type Route struct {
  25. handler Handler
  26. regex *regexp.Regexp
  27. varNames []string
  28. }
  29. func NewRoute(path string, handler HandlerFunc) *Route {
  30. r := &Route{
  31. handler: handler,
  32. }
  33. path = strings.TrimPrefix(path, `/`)
  34. if strings.HasSuffix(path, `/`) {
  35. path = strings.TrimSuffix(path, `/`)
  36. }
  37. routeParts := strings.Split(path, "/")
  38. var routePattern string = `^`
  39. for _, routePart := range routeParts {
  40. if strings.HasPrefix(routePart, `{`) && strings.HasSuffix(routePart, `}`) {
  41. routePattern += RouteWithParamsPattern
  42. routePart = strings.TrimPrefix(path, `{`)
  43. routePart = strings.TrimSuffix(path, `}`)
  44. r.varNames = append(r.varNames, routePart)
  45. } else {
  46. routePattern += RouteOnlyPrefixPattern + routePart
  47. }
  48. }
  49. routePattern += RouteSuffixPattern
  50. r.regex = regexp.MustCompile(routePattern)
  51. return r
  52. }