Skouter mortgage estimates. Web application with view written in PHP and Vue, but controller and models in Go.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

skouter.go 1.5 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. }
  23. var pages = map[string]Page {
  24. "home": cache("home", "Home"),
  25. "terms": cache("terms", "Terms and Conditions"),
  26. }
  27. func cache(name string, title string) Page {
  28. var p = []string{"master.tpl", paths[name]}
  29. tpl := template.Must(template.ParseFiles(p...))
  30. return Page{tpl: tpl,
  31. Title: title,
  32. Name: name,
  33. }
  34. }
  35. func (page Page) Render(w http.ResponseWriter) {
  36. err := page.tpl.Execute(w, page)
  37. if err != nil {
  38. log.Print(err)
  39. }
  40. }
  41. func match(path, pattern string, args *[]string) bool {
  42. relock.Lock()
  43. defer relock.Unlock()
  44. regex := regexen[pattern]
  45. if regex == nil {
  46. regex = regexp.MustCompile("^" + pattern + "$")
  47. regexen[pattern] = regex
  48. }
  49. matches := regex.FindStringSubmatch(path)
  50. if len(matches) <= 0 {
  51. return false
  52. }
  53. *args = matches[1:]
  54. return true
  55. }
  56. func route(w http.ResponseWriter, r *http.Request) {
  57. var page Page
  58. var args []string
  59. p := r.URL.Path
  60. switch {
  61. case r.Method == "GET" && match(p, "/", &args):
  62. page = pages[ "home" ]
  63. case match(p, "/terms", &args):
  64. page = pages[ "terms" ]
  65. default:
  66. http.NotFound(w, r)
  67. return
  68. }
  69. page.Render(w)
  70. }
  71. func main() {
  72. http.HandleFunc("/", route)
  73. log.Fatal(http.ListenAndServe(address, nil))
  74. }