handlers.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package server
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "git.linuxit.ro/turos.robert/mynotes/lib/inout"
  9. )
  10. func Wildcard(w http.ResponseWriter, r *http.Request, s *Server) {
  11. baseDir := "./templates/"
  12. endpoint := strings.TrimPrefix(r.URL.Path, "/")
  13. if action, ok := findRoute(r.URL.Path, s.Routes); ok {
  14. handlers := makeFuncMap()
  15. handler, exists := handlers[action]
  16. if !exists {
  17. resp, code := inout.ParseTemplate("templates/error.tmpl", fmt.Errorf("handler %s not found", action))
  18. w.Header().Set("Content-Type", "text/html")
  19. w.WriteHeader(code)
  20. w.Write(resp)
  21. return
  22. }
  23. handler(w, r)
  24. return
  25. }
  26. if endpoint == "" {
  27. endpoint = "index.html"
  28. }
  29. path := filepath.Join(baseDir, endpoint)
  30. _, err := os.Stat(path)
  31. if err != nil {
  32. w.Header().Set("Content-Type", "text/html")
  33. resp, code := inout.ParseTemplate("templates/error.tmpl", err)
  34. w.WriteHeader(code)
  35. w.Write(resp)
  36. return
  37. }
  38. w.Write(inout.FileToBytes(path))
  39. }
  40. func findRoute(path string, routes map[string]string) (string, bool) {
  41. // 1. exact match
  42. if action, ok := routes[path]; ok {
  43. return action, true
  44. }
  45. // 2. longest prefix match
  46. longest := ""
  47. action := ""
  48. for route, a := range routes {
  49. if strings.HasPrefix(path, route) {
  50. if len(route) > len(longest) {
  51. longest = route
  52. action = a
  53. }
  54. }
  55. }
  56. if longest != "" {
  57. return action, true
  58. }
  59. return "", false
  60. }
  61. func makeFuncMap() map[string]hfunc {
  62. handlers := map[string]hfunc{
  63. "VIEW_NOTE": func(w http.ResponseWriter, r *http.Request) {
  64. note := r.URL.Query().Get("note")
  65. Notes(w, r, note)
  66. },
  67. "EDIT_NOTE": func(w http.ResponseWriter, r *http.Request) {
  68. note := r.URL.Query().Get("note")
  69. EditNotes(w, r, note)
  70. },
  71. "LIST_NOTES": func(w http.ResponseWriter, r *http.Request) {
  72. srv := Server{}
  73. err := inout.FileToObj("mynotes_cfg.json", &srv)
  74. if err != nil {
  75. srv.Err = err
  76. }
  77. ListNotes(w, r, &srv)
  78. },
  79. "API": func(w http.ResponseWriter, r *http.Request) {
  80. srv := Server{}
  81. err := inout.FileToObj("mynotes_cfg.json", &srv)
  82. if err != nil {
  83. srv.Err = err
  84. }
  85. API(w, r, &srv)
  86. },
  87. "MKDOWN_CONVERT": MDToHTML,
  88. }
  89. return handlers
  90. }