web_handlers.go 2.4 KB

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