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.

73 lines
1.7 KiB

7 years ago
  1. package wrouter
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "git.aiterp.net/gisle/notebook3/session"
  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. defer req.Body.Close()
  25. // Allow REST for clients of yore
  26. if req.Header.Get("X-Method") != "" {
  27. req.Method = strings.ToUpper(req.Header.Get("X-Method"))
  28. }
  29. // Resolve session cookies
  30. var user *auth.User
  31. cookie, err := req.Cookie(session.CookieName)
  32. if cookie != nil && err == nil {
  33. sess := auth.FindSession(cookie.Value)
  34. if sess != nil {
  35. user = auth.FindUser(sess.UserID)
  36. }
  37. }
  38. for index, route := range router.routes {
  39. path := router.paths[route]
  40. if strings.HasPrefix(strings.ToLower(req.URL.Path), path) {
  41. // Just so the handler can replace the path properly in case of case
  42. // insensitive clients getting fancy on it.
  43. path = req.URL.Path[:len(path)]
  44. // Attach a little something for testing
  45. w.Header().Set("X-Route-Path", path)
  46. w.Header().Set("X-Route-Index", fmt.Sprint(index))
  47. if route.Handle(path, w, req, user) {
  48. return
  49. }
  50. }
  51. }
  52. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  53. w.WriteHeader(404)
  54. }
  55. func (router *Router) Listen(host string, port int) error {
  56. return http.ListenAndServe(fmt.Sprintf("%s:%d", host, port), router)
  57. }