Skouter mortgage estimates. Web application with view written in PHP and Vue, but controller and models in Go.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

96 lines
1.8 KiB

  1. package main
  2. import (
  3. "net/http"
  4. "log"
  5. "sync"
  6. "regexp"
  7. "html/template"
  8. )
  9. type Page struct {
  10. tpl *template.Template
  11. Title string
  12. Name string
  13. }
  14. var (
  15. regexen = make(map[string]*regexp.Regexp)
  16. relock sync.Mutex
  17. address = "127.0.0.1:8001"
  18. )
  19. var paths = map[string]string {
  20. "home": "home.tpl",
  21. "terms": "terms.tpl",
  22. "app": "app.tpl",
  23. }
  24. var pages = map[string]Page {
  25. "home": cache("home", "Home"),
  26. "terms": cache("terms", "Terms and Conditions"),
  27. "app": cache("app", "App"),
  28. }
  29. func cache(name string, title string) Page {
  30. var p = []string{"master.tpl", paths[name]}
  31. tpl := template.Must(template.ParseFiles(p...))
  32. return Page{tpl: tpl,
  33. Title: title,
  34. Name: name,
  35. }
  36. }
  37. func (page Page) Render(w http.ResponseWriter) {
  38. err := page.tpl.Execute(w, page)
  39. if err != nil {
  40. log.Print(err)
  41. }
  42. }
  43. func match(path, pattern string, args *[]string) bool {
  44. relock.Lock()
  45. defer relock.Unlock()
  46. regex := regexen[pattern]
  47. if regex == nil {
  48. regex = regexp.MustCompile("^" + pattern + "$")
  49. regexen[pattern] = regex
  50. }
  51. matches := regex.FindStringSubmatch(path)
  52. if len(matches) <= 0 {
  53. return false
  54. }
  55. *args = matches[1:]
  56. return true
  57. }
  58. func route(w http.ResponseWriter, r *http.Request) {
  59. var page Page
  60. var args []string
  61. p := r.URL.Path
  62. switch {
  63. case r.Method == "GET" && match(p, "/", &args):
  64. page = pages[ "home" ]
  65. case match(p, "/terms", &args):
  66. page = pages[ "terms" ]
  67. case match(p, "/app", &args):
  68. page = pages[ "app" ]
  69. case match(p, "/assets", &args):
  70. page = pages[ "app" ]
  71. default:
  72. http.NotFound(w, r)
  73. return
  74. }
  75. page.Render(w)
  76. }
  77. func main() {
  78. files := http.FileServer(http.Dir(""))
  79. http.Handle("/assets/", files)
  80. http.HandleFunc("/", route)
  81. log.Fatal(http.ListenAndServe(address, nil))
  82. }