Developer Center website. https://developers.write.as
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.

69 lines
1.5 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/writeas/web-core/log"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "runtime/debug"
  9. "time"
  10. )
  11. func viewPage(w http.ResponseWriter, r *http.Request) {
  12. start := time.Now()
  13. defer func() {
  14. if e := recover(); e != nil {
  15. log.Error("%s: %s", e, debug.Stack())
  16. http.Error(w, "Error", http.StatusInternalServerError)
  17. }
  18. log.Info(fmt.Sprintf("\"%s %s\" %s \"%s\"", r.Method, r.RequestURI, time.Since(start), r.UserAgent()))
  19. }()
  20. name := r.URL.Path[1:]
  21. if name == "" {
  22. name = "index"
  23. }
  24. // Make sure the page exists
  25. if _, err := os.Stat(filepath.Join(pagesDir, name+".tmpl")); os.IsNotExist(err) {
  26. log.Info(filepath.Join(pagesDir, name, "index.tmpl"))
  27. if _, err := os.Stat(filepath.Join(pagesDir, name, "index.tmpl")); os.IsNotExist(err) {
  28. t, err := getTemplate("404")
  29. if err != nil {
  30. http.Error(w, err.Error(), http.StatusInternalServerError)
  31. return
  32. }
  33. w.WriteHeader(http.StatusNotFound)
  34. err = t.ExecuteTemplate(w, "base", nil)
  35. if err != nil {
  36. log.Info("Unable to render 404 page: %s", err)
  37. }
  38. return
  39. } else {
  40. name = filepath.Join(name, "index")
  41. log.Info("name is now %s", name)
  42. }
  43. }
  44. // Render the page
  45. t, err := getTemplate(name)
  46. if err != nil {
  47. http.Error(w, err.Error(), http.StatusInternalServerError)
  48. return
  49. }
  50. p := struct {
  51. Path string
  52. }{
  53. Path: name,
  54. }
  55. err = t.ExecuteTemplate(w, "base", p)
  56. if err != nil {
  57. http.Error(w, err.Error(), http.StatusInternalServerError)
  58. return
  59. }
  60. }