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.

88 lines
1.9 KiB

  1. package main
  2. import (
  3. "html/template"
  4. "log"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. padArchiver ".."
  10. "github.com/gorilla/mux"
  11. )
  12. type ItemModel struct {
  13. Name string
  14. Path string
  15. IsDir bool
  16. Content template.HTML
  17. }
  18. type MenuModel struct {
  19. PageTitle string
  20. Items []ItemModel
  21. }
  22. func main() {
  23. router := mux.NewRouter()
  24. router.HandleFunc("/", getDir).Methods("GET")
  25. router.HandleFunc("/dir/{path}", getDir).Methods("GET")
  26. router.HandleFunc("/page/{path}", getPage).Methods("GET")
  27. log.Println("padArchiver web server running")
  28. log.Print("port: 8080")
  29. log.Fatal(http.ListenAndServe(":8080", router))
  30. }
  31. func generateMenu(dirpath string) MenuModel {
  32. var menuPage MenuModel
  33. menuPage.PageTitle = "padArchiver - Menu"
  34. _ = filepath.Walk(padArchiver.Storage+dirpath, func(path string, f os.FileInfo, err error) error {
  35. if path != padArchiver.Storage {
  36. path = strings.Replace(path, padArchiver.Storage, "", -1)
  37. var item ItemModel
  38. item.Name = path
  39. path = strings.Replace(path, "/", "%", -1)
  40. if f.IsDir() {
  41. item.Path = "/dir/" + path
  42. } else {
  43. item.Path = "/page/" + path
  44. }
  45. item.IsDir = f.IsDir()
  46. menuPage.Items = append(menuPage.Items, item)
  47. }
  48. return nil
  49. })
  50. return menuPage
  51. }
  52. func getDir(w http.ResponseWriter, r *http.Request) {
  53. vars := mux.Vars(r)
  54. var dirpath string
  55. if _, ok := vars["path"]; ok {
  56. dirpath = vars["path"]
  57. dirpath = strings.Replace(dirpath, "%", "/", -1)
  58. }
  59. menuPage := generateMenu(dirpath)
  60. tmpl := template.Must(template.ParseFiles("templates/menuTemplate.html"))
  61. tmpl.Execute(w, menuPage)
  62. }
  63. func getPage(w http.ResponseWriter, r *http.Request) {
  64. vars := mux.Vars(r)
  65. path := vars["path"]
  66. path = strings.Replace(path, "%", "/", -1)
  67. path = padArchiver.Storage + path
  68. content, err := fileToHTML(path)
  69. check(err)
  70. var item ItemModel
  71. item.Name = path
  72. item.Content = template.HTML(content)
  73. tmpl := template.Must(template.ParseFiles("templates/pageTemplate.html"))
  74. tmpl.Execute(w, item)
  75. }