Răsfoiți Sursa

1.清理模板文件及多余接口 2.区分连接正常断开,还是出现错误

shizhongqi 10 luni în urmă
părinte
comite
cf0cbffc7d
7 a modificat fișierele cu 7 adăugiri și 254 ștergeri
  1. 0 11
      main.go
  2. 0 116
      static/css/styles.css
  3. 0 59
      static/js/chat.js
  4. 0 19
      templates/chat.html
  5. 0 18
      templates/index.html
  6. 0 29
      templates/template_handler.go
  7. 7 2
      wsClient/client.go

+ 0 - 11
main.go

@@ -4,7 +4,6 @@ package main
 
 import (
 	"chatapp/logger"
-	"chatapp/templates"
 	"chatapp/wsClient"
 	"flag"
 	"fmt"
@@ -52,16 +51,6 @@ func main() {
 		defer wsClient.CloseRedis()
 	}
 
-	// 设置静态文件服务器,处理 CSS、JS 等静态资源
-	// StripPrefix 会移除 URL 前缀 "/static/",然后从 "static" 目录提供文件
-	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
-
-	// 主页路由,渲染 index.html 模板
-	http.Handle("/", &templates.TemplateHandler{Filename: "index.html"})
-
-	// 聊天页面路由,渲染 chat.html 模板
-	http.Handle("/chat", &templates.TemplateHandler{Filename: "chat.html"})
-
 	// Handle all websocket connections for chat rooms dynamically
 	http.HandleFunc("/room", func(w http.ResponseWriter, r *http.Request) {
 		log.Info().Msg("--------------------------------")

+ 0 - 116
static/css/styles.css

@@ -1,116 +0,0 @@
-/* General page styles */
-body {
-  font-family: Arial, sans-serif;
-  background-color: #f1f1f1;
-  margin: 0;
-  padding: 0;
-}
-
-/* Header for chat.html */
-header {
-  background-color: #333;
-  color: #fff;
-  padding: 10px;
-  text-align: center;
-  font-size: 24px;
-}
-
-/* Message display */
-#messages {
-  height: 80vh;
-  overflow-y: auto;
-  padding: 10px;
-}
-
-.message-container {
-  margin-bottom: 15px;
-}
-
-.username {
-  font-weight: bold;
-  margin-bottom: 3px;
-  color: #333;
-}
-
-.message {
-  background-color: #e0e0e0;
-  padding: 10px;
-  border-radius: 5px;
-  display: inline-block;
-  max-width: 70%;
-  word-wrap: break-word;
-}
-
-/* Chat input section */
-.chat-input {
-  display: flex;
-  padding: 10px;
-  background-color: #fff;
-  border-top: 1px solid #ccc;
-}
-
-.chat-input input[type="text"] {
-  flex: 1;
-  padding: 10px;
-  font-size: 16px;
-  border: 1px solid #ccc;
-  border-radius: 4px;
-}
-
-.chat-input button {
-  padding: 10px 20px;
-  margin-left: 10px;
-  font-size: 16px;
-  background-color: #333;
-  color: #fff;
-  border: none;
-  border-radius: 4px;
-  cursor: pointer;
-}
-
-.chat-input button:hover {
-  background-color: #555;
-}
-
-/* Styles specific to index.html */
-.index-body {
-  display: flex;
-  flex-direction: column;
-  align-items: center;
-  justify-content: center;
-  height: 100vh;
-}
-
-.index-body h1 {
-  margin-bottom: 20px;
-  color: #333;
-}
-
-.index-body form {
-  display: flex;
-  flex-direction: column;
-  align-items: center;
-}
-
-.index-body input[type="text"] {
-  padding: 10px;
-  font-size: 16px;
-  width: 250px;
-  margin-bottom: 10px;
-  border: 1px solid #ccc;
-  border-radius: 4px;
-}
-
-.index-body button {
-  padding: 10px 20px;
-  font-size: 16px;
-  background-color: #333;
-  color: #fff;
-  border: none;
-  border-radius: 4px;
-  cursor: pointer;
-}
-
-.index-body button:hover {
-  background-color: #555;
-}

+ 0 - 59
static/js/chat.js

@@ -1,59 +0,0 @@
-const params = new URLSearchParams(window.location.search);
-const room = params.get("room");
-
-if (!room) {
-  alert("No room specified. Redirecting to homepage...");
-  window.location.href = "/";
-}
-
-const socket = new WebSocket(`ws://${location.host}/room?room=${room}`);
-
-socket.onmessage = (event) => {
-  try {
-    const data = JSON.parse(event.data);
-
-    // Create the container div
-    const msgContainer = document.createElement("div");
-    msgContainer.classList.add("message-container");
-
-    // Create the username div
-    const usernameDiv = document.createElement("div");
-    usernameDiv.classList.add("username");
-    usernameDiv.textContent = data.name;
-
-    // Create the message div
-    const messageDiv = document.createElement("div");
-    messageDiv.classList.add("message");
-    messageDiv.textContent = data.message;
-
-    // Append username and message in correct order
-    msgContainer.appendChild(usernameDiv);
-    msgContainer.appendChild(messageDiv);
-
-    // Append the whole message container to the messages div
-    document.getElementById("messages").appendChild(msgContainer);
-
-    // Auto-scroll
-    const messagesDiv = document.getElementById("messages");
-    messagesDiv.scrollTop = messagesDiv.scrollHeight;
-
-  } catch (err) {
-    console.error("Invalid JSON received:", event.data);
-  }
-};
-
-function sendMessage() {
-  const input = document.getElementById("msg");
-  if (input.value.trim() !== "") {
-    socket.send(input.value);
-    input.value = "";
-  }
-}
-
-document.getElementById("sendBtn").addEventListener("click", sendMessage);
-
-document.getElementById("msg").addEventListener("keyup", function (event) {
-  if (event.key === "Enter") {
-    sendMessage();
-  }
-});

+ 0 - 19
templates/chat.html

@@ -1,19 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-  <meta charset="UTF-8" />
-  <title>Chat Room</title>
-  <link rel="stylesheet" href="/static/css/styles.css" />
-</head>
-<body class="chat-body">
-  <header>Chat Room</header>
-  <div id="messages"></div>
-
-  <div class="chat-input">
-    <input id="msg" type="text" placeholder="Type a message..." />
-    <button id="sendBtn">Send</button>
-  </div>
-
-  <script src="/static/js/chat.js"></script>
-</body>
-</html>

+ 0 - 18
templates/index.html

@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-  <meta charset="UTF-8" />
-  <title>Select a Chat Room</title>
-  <link rel="stylesheet" href="/static/css/styles.css" />
-</head>
-<body class="index-body">
-  <h1>Join a Chat Room</h1>
-  <form action="/chat" method="get">
-    <input type="text" name="room" placeholder="Enter channel name..." required />
-    <button type="submit">Join</button>
-  </form>
-
-  <!-- Optional: index.js if you want any client JS here -->
-  <script src="/static/js/index.js"></script>
-</body>
-</html>

+ 0 - 29
templates/template_handler.go

@@ -1,29 +0,0 @@
-// Package templates 提供 HTML 模板的处理功能
-package templates
-
-import (
-	"net/http"
-	"path/filepath"
-	"sync"
-	"text/template"
-)
-
-// TemplateHandler 负责处理 HTML 模板的渲染
-type TemplateHandler struct {
-	once     sync.Once         // 确保模板只被解析一次
-	Filename string            // 模板文件名
-	templ    *template.Template // 解析后的模板对象
-}
-
-// ServeHTTP 处理 HTTP 请求并渲染模板
-// 实现了 http.Handler 接口
-func (t *TemplateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
-	// 使用 sync.Once 确保模板只被解析一次,避免重复解析带来的性能开销
-	t.once.Do(func() {
-		// 解析模板文件,如果失败会 panic
-		t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.Filename)))
-	})
-
-	// 执行模板渲染,将请求对象作为数据传递给模板
-	t.templ.Execute(w, r)
-}

+ 7 - 2
wsClient/client.go

@@ -59,8 +59,12 @@ func (c *Client) read() {
 		_, msg, err := c.socket.ReadMessage()
 		// break if there is an error
 		if err != nil {
-			log.Error().Err(err).Str("client", c.name).Msg("读取WebSocket消息失败")
-			return
+			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
+				log.Error().Err(err).Str("client", c.name).Msg("读取WebSocket消息失败")
+			} else {
+				log.Info().Err(err).Str("client", c.name).Msg("WebSocket连接正常关闭")
+			}
+			break
 		}
 
 		// 记录原始消息内容用于调试
@@ -104,6 +108,7 @@ func (c *Client) write() {
 	for msg := range c.receive {
 		err := c.socket.WriteMessage(websocket.TextMessage, msg)
 		if err != nil {
+			log.Error().Err(err).Str("client", c.name).Msg("写入WebSocket消息失败")
 			return
 		}
 	}