A web blog and personal homepage engine written in Go.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

74 lines
1.3 KiB

  1. package glue
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "sort"
  7. "sync"
  8. "github.com/gorilla/mux"
  9. )
  10. // Endpoint is a handler attached to a path.
  11. type Endpoint struct {
  12. Path string
  13. Methods []string
  14. Middleware []mux.MiddlewareFunc
  15. Handler func(w http.ResponseWriter, r *http.Request)
  16. }
  17. var (
  18. registry = map[string]Endpoint{}
  19. registryLock sync.RWMutex
  20. )
  21. //////////////////////////
  22. // Register a controller.
  23. func Register(e Endpoint) {
  24. registryLock.Lock()
  25. if _, ok := registry[e.Path]; ok {
  26. panic(fmt.Sprintf("Route Registry: path '%s' already registered", e.Path))
  27. }
  28. registry[e.Path] = e
  29. registryLock.Unlock()
  30. log.Printf("Register: %s", e.Path)
  31. }
  32. // GetControllers returns all the routes and handler functions.
  33. func GetControllers() []Endpoint {
  34. registryLock.RLock()
  35. defer registryLock.RUnlock()
  36. // Sort the endpoints by longest first.
  37. var keys = make([]string, len(registry))
  38. var i int
  39. for key := range registry {
  40. keys[i] = key
  41. i++
  42. }
  43. sort.Sort(byLength(keys))
  44. result := make([]Endpoint, len(registry))
  45. for i, key := range keys {
  46. result[i] = registry[key]
  47. }
  48. return result
  49. }
  50. type byLength []string
  51. func (s byLength) Len() int {
  52. return len(s)
  53. }
  54. func (s byLength) Swap(i, j int) {
  55. s[i], s[j] = s[j], s[i]
  56. }
  57. func (s byLength) Less(i, j int) bool {
  58. // Sort longest over shortest.
  59. return len(s[j]) < len(s[i])
  60. }