web_handlers.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package main
  2. import (
  3. "encoding/json"
  4. "io/fs"
  5. "net/http"
  6. "strings"
  7. )
  8. type LoginReq struct {
  9. Username string `json:"username"`
  10. Password string `json:"password"`
  11. }
  12. type LoginResp struct {
  13. Success bool `json:"success"`
  14. }
  15. func WebLoginHandler(w http.ResponseWriter, r *http.Request) {
  16. if r.Method != http.MethodPost {
  17. w.WriteHeader(http.StatusMethodNotAllowed)
  18. return
  19. }
  20. var req LoginReq
  21. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  22. w.WriteHeader(http.StatusBadRequest)
  23. return
  24. }
  25. ok := req.Username == "admin" && req.Password == "admin123456"
  26. if ok {
  27. sessionID := WebCreateSession()
  28. WebAddSession(sessionID)
  29. http.SetCookie(w, &http.Cookie{
  30. Name: "session_id",
  31. Value: sessionID,
  32. Path: "/",
  33. HttpOnly: true,
  34. SameSite: http.SameSiteStrictMode,
  35. })
  36. }
  37. w.Header().Set("Content-Type", "application/json")
  38. json.NewEncoder(w).Encode(LoginResp{Success: ok})
  39. }
  40. func WebLogoutHandler(w http.ResponseWriter, r *http.Request) {
  41. if cookie, err := r.Cookie("session_id"); err == nil {
  42. sessionMu.Lock()
  43. delete(sessions, cookie.Value)
  44. sessionMu.Unlock()
  45. }
  46. http.SetCookie(w, &http.Cookie{
  47. Name: "session_id",
  48. Value: "",
  49. Path: "/",
  50. MaxAge: -1,
  51. })
  52. http.Redirect(w, r, "/", http.StatusFound)
  53. }
  54. func (ui *WebUI) WebRootHandler(w http.ResponseWriter, r *http.Request) {
  55. path := r.URL.Path
  56. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  57. w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
  58. w.Header().Set("Pragma", "no-cache")
  59. w.Header().Set("Expires", "0")
  60. // 1, 未登录时, 只能看登录页
  61. if !WebCheckSession(r) {
  62. data, err := fs.ReadFile(ui.fs, "login.html")
  63. if err != nil {
  64. http.NotFound(w, r)
  65. } else {
  66. w.Write(data)
  67. }
  68. return
  69. }
  70. // 2, 登录成功, 展示导航首页
  71. if path == "/" {
  72. data, err := fs.ReadFile(ui.fs, "index.html")
  73. if err != nil {
  74. http.NotFound(w, r)
  75. } else {
  76. w.Write(data)
  77. }
  78. return
  79. }
  80. // 3, 在网站内跳转其它功能页
  81. if strings.HasPrefix(path, "/pages/") { // path 形如 "/pages/page1.html"
  82. data, err := fs.ReadFile(ui.fs, path[1:])
  83. if err != nil {
  84. http.NotFound(w, r)
  85. } else {
  86. w.Write(data)
  87. }
  88. return
  89. }
  90. // 4, 访问其它不认识的页面时
  91. http.NotFound(w, r)
  92. }