Core functionality for new aiterp.net servers
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.

100 lines
2.4 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package wrouter
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "git.aiterp.net/gisle/wrouter/auth"
  8. )
  9. type Route interface {
  10. Handle(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool
  11. }
  12. type Router struct {
  13. paths map[Route]string
  14. routes []Route
  15. }
  16. func (router *Router) Route(path string, route Route) {
  17. if router.paths == nil {
  18. router.paths = make(map[Route]string, 16)
  19. }
  20. router.paths[route] = path
  21. router.routes = append(router.routes, route)
  22. }
  23. func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  24. req.ParseForm()
  25. defer req.Body.Close()
  26. // Allow REST for clients of yore
  27. if req.Header.Get("X-Method") != "" {
  28. req.Method = strings.ToUpper(req.Header.Get("X-Method"))
  29. }
  30. // Resolve session cookies
  31. var user *auth.User
  32. var sess *auth.Session
  33. cookie, err := req.Cookie(auth.SessionCookieName)
  34. if cookie != nil && err == nil {
  35. sess = auth.FindSession(cookie.Value)
  36. if sess != nil {
  37. user, _ = auth.FindUser(sess.UserID)
  38. }
  39. }
  40. for index, route := range router.routes {
  41. path := router.paths[route]
  42. if strings.HasPrefix(strings.ToLower(req.URL.Path), path) {
  43. // Just so the handler can replace the path properly in case of case
  44. // insensitive clients getting fancy on it.
  45. path = req.URL.Path[:len(path)]
  46. // Attach a little something for testing
  47. w.Header().Set("X-Route-Path", path)
  48. w.Header().Set("X-Route-Index", fmt.Sprint(index))
  49. if route.Handle(path, w, req, user) {
  50. if user != nil && user.LoggedOut() {
  51. auth.CloseSession(sess.ID)
  52. }
  53. return
  54. }
  55. }
  56. }
  57. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  58. w.WriteHeader(404)
  59. w.Write([]byte("Not Found: " + req.URL.Path))
  60. }
  61. func (router *Router) Resource(mount string, list, create ResourceFunc, get, update, delete ResourceIDFunc) {
  62. router.Route(mount, NewResource(list, create, get, update, delete))
  63. }
  64. func (router *Router) Static(mount string, filePath string) {
  65. router.Route(mount, NewStatic(filePath))
  66. }
  67. func (router *Router) Function(mount string, function FunctionHandlerFunc) {
  68. router.Route(mount, &functionHandler{function})
  69. }
  70. func (router *Router) Listen(host string, port int) (*http.Server, error) {
  71. srv := &http.Server{
  72. Addr: fmt.Sprintf("%s:%d", host, port),
  73. ReadTimeout: 5 * time.Second,
  74. WriteTimeout: 10 * time.Second,
  75. IdleTimeout: 120 * time.Second,
  76. Handler: router,
  77. }
  78. return srv, srv.ListenAndServe()
  79. }