middleware.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "time"
  6. )
  7. func mainPage(w http.ResponseWriter, r *http.Request) {
  8. session, err := r.Cookie("session_id")
  9. // учебный пример! это не проверка авторизации!
  10. loggedIn := (err != http.ErrNoCookie)
  11. if loggedIn {
  12. fmt.Fprintln(w, `<a href="/logout">logout</a>`)
  13. fmt.Fprintln(w, "Welcome, "+session.Value)
  14. } else {
  15. fmt.Fprintln(w, `<a href="/login">login</a>`)
  16. fmt.Fprintln(w, "You need to login")
  17. }
  18. }
  19. func loginPage(w http.ResponseWriter, r *http.Request) {
  20. expiration := time.Now().Add(10 * time.Hour)
  21. cookie := http.Cookie{
  22. Name: "session_id",
  23. Value: "rvasily",
  24. Expires: expiration,
  25. }
  26. http.SetCookie(w, &cookie)
  27. http.Redirect(w, r, "/", http.StatusFound)
  28. }
  29. func logoutPage(w http.ResponseWriter, r *http.Request) {
  30. session, err := r.Cookie("session_id")
  31. if err == http.ErrNoCookie {
  32. http.Redirect(w, r, "/", http.StatusFound)
  33. return
  34. }
  35. session.Expires = time.Now().AddDate(0, 0, -1)
  36. http.SetCookie(w, session)
  37. http.Redirect(w, r, "/", http.StatusFound)
  38. }
  39. // -----------
  40. func adminIndex(w http.ResponseWriter, r *http.Request) {
  41. fmt.Fprintln(w, `<a href="/">site index</a>`)
  42. fmt.Fprintln(w, "Admin main page")
  43. }
  44. func panicPage(w http.ResponseWriter, r *http.Request) {
  45. panic("this must me recovered")
  46. }
  47. // -----------
  48. func pageWithAllChecks(w http.ResponseWriter, r *http.Request) {
  49. defer func() {
  50. if err := recover(); err != nil {
  51. fmt.Println("recovered", err)
  52. http.Error(w, "Internal server error", 500)
  53. }
  54. }()
  55. defer func(start time.Time) {
  56. fmt.Printf("[%s] %s, %s %s\n",
  57. r.Method, r.RemoteAddr, r.URL.Path, time.Since(start))
  58. }(time.Now())
  59. _, err := r.Cookie("session_id")
  60. // учебный пример! это не проверка авторизации!
  61. if err != nil {
  62. fmt.Println("no auth at", r.URL.Path)
  63. http.Redirect(w, r, "/", http.StatusFound)
  64. return
  65. }
  66. // your logic
  67. }
  68. // -----------
  69. func adminAuthMiddleware(next http.Handler) http.Handler {
  70. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  71. fmt.Println("adminAuthMiddleware", r.URL.Path)
  72. _, err := r.Cookie("session_id")
  73. // учебный пример! это не проверка авторизации!
  74. if err != nil {
  75. fmt.Println("no auth at", r.URL.Path)
  76. http.Redirect(w, r, "/", http.StatusFound)
  77. return
  78. }
  79. next.ServeHTTP(w, r)
  80. })
  81. }
  82. func accessLogMiddleware(next http.Handler) http.Handler {
  83. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  84. fmt.Println("accessLogMiddleware", r.URL.Path)
  85. start := time.Now()
  86. next.ServeHTTP(w, r)
  87. fmt.Printf("[%s] %s, %s %s\n",
  88. r.Method, r.RemoteAddr, r.URL.Path, time.Since(start))
  89. })
  90. }
  91. func panicMiddleware(next http.Handler) http.Handler {
  92. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  93. fmt.Println("panicMiddleware", r.URL.Path)
  94. defer func() {
  95. if err := recover(); err != nil {
  96. fmt.Println("recovered", err)
  97. http.Error(w, "Internal server error", 500)
  98. }
  99. }()
  100. next.ServeHTTP(w, r)
  101. })
  102. }
  103. // -----------
  104. func main() {
  105. adminMux := http.NewServeMux()
  106. adminMux.HandleFunc("/admin/", adminIndex)
  107. adminMux.HandleFunc("/admin/panic", panicPage)
  108. // set middleware
  109. adminHandler := adminAuthMiddleware(adminMux)
  110. siteMux := http.NewServeMux()
  111. siteMux.Handle("/admin/", adminHandler)
  112. siteMux.HandleFunc("/login", loginPage)
  113. siteMux.HandleFunc("/logout", logoutPage)
  114. siteMux.HandleFunc("/", mainPage)
  115. // set middleware
  116. siteHandler := accessLogMiddleware(siteMux)
  117. siteHandler = panicMiddleware(siteHandler)
  118. fmt.Println("starting server at :8080")
  119. http.ListenAndServe(":8080", siteHandler)
  120. }