fix swagger

This commit is contained in:
2026-01-18 19:07:41 +08:00
parent 20ed44aa74
commit 7d3915aae2
319 changed files with 7888 additions and 4559 deletions

View File

@@ -1,7 +0,0 @@
ROOT_DIR = $(shell pwd)
NAMESPACE = "default"
DEPLOY_NAME = "template-single"
DOCKER_NAME = "template-single"
include ./hack/hack-cli.mk
include ./hack/hack.mk

View File

@@ -7,7 +7,7 @@ package containment
import (
"context"
"leke/api/containment/v1"
"TrangleAgent/api/containment/v1"
)
type IContainmentV1 interface {

View File

@@ -1,8 +1,8 @@
package v1
import (
"leke/internal/model"
"leke/internal/model/response"
"TrangleAgent/internal/model"
"TrangleAgent/internal/model/response"
"github.com/gogf/gf/v2/frame/g"
)

View File

@@ -7,7 +7,7 @@ package department
import (
"context"
"leke/api/department/v1"
"TrangleAgent/api/department/v1"
)
type IDepartmentV1 interface {

View File

@@ -1,7 +1,7 @@
package v1
import (
"leke/internal/model/response"
"TrangleAgent/internal/model/response"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"

View File

@@ -7,7 +7,7 @@ package forum
import (
"context"
"leke/api/forum/v1"
"TrangleAgent/api/forum/v1"
)
type IForumV1 interface {

View File

@@ -3,7 +3,7 @@ package v1
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"leke/internal/model/response"
"TrangleAgent/internal/model/response"
)
// ForumCommentsCreateReq 创建评论请求

View File

@@ -3,7 +3,7 @@ package v1
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"
"leke/internal/model/response"
"TrangleAgent/internal/model/response"
)
// ForumPostsCreateReq 创建帖子请求

View File

@@ -7,7 +7,7 @@ package login
import (
"context"
"leke/api/login/v1"
"TrangleAgent/api/login/v1"
)
type ILoginV1 interface {

View File

@@ -7,7 +7,7 @@ package room
import (
"context"
"leke/api/room/v1"
"TrangleAgent/api/room/v1"
)
type IRoomV1 interface {

View File

@@ -1,8 +1,8 @@
package v1
import (
"leke/internal/model"
"leke/internal/model/response"
"TrangleAgent/internal/model"
"TrangleAgent/internal/model/response"
"github.com/gogf/gf/v2/frame/g"
)

View File

@@ -7,7 +7,7 @@ package user
import (
"context"
"leke/api/user/v1"
"TrangleAgent/api/user/v1"
)
type IUserV1 interface {

View File

@@ -1,7 +1,7 @@
package v1
import (
"leke/internal/model/response"
"TrangleAgent/internal/model/response"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"

View File

@@ -2,7 +2,7 @@ package v1
import (
"github.com/gogf/gf/v2/frame/g"
"leke/internal/model/response"
"TrangleAgent/internal/model/response"
)
type RoleCreateReq struct {

View File

@@ -1,7 +1,7 @@
package v1
import (
"leke/internal/model/response"
"TrangleAgent/internal/model/response"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gtime"

View File

@@ -2,7 +2,7 @@ package v1
import (
"github.com/gogf/gf/v2/frame/g"
"leke/internal/model/response"
"TrangleAgent/internal/model/response"
)
// TraceListReq 查询轨迹列表请求参数

View File

@@ -1,8 +1,8 @@
package v1
import (
"leke/internal/model"
"leke/internal/model/response"
"TrangleAgent/internal/model"
"TrangleAgent/internal/model/response"
"github.com/gogf/gf/v2/frame/g"
)

View File

@@ -1,4 +1,4 @@
module leke
module TrangleAgent
go 1.24.0

View File

@@ -1,5 +1,3 @@
# CLI tool, only in development environment.
# https://goframe.org/docs/cli
gfcli:
gen:
dao:
@@ -11,3 +9,7 @@ gfcli:
build: "-a amd64 -s linux -p temp -ew"
tagPrefixes:
- my.image.pub/my-app
server:
address: ":8000"
openapiPath: "/api.json"
swaggerPath: "/swagger"

View File

@@ -1,12 +1,13 @@
package cmd
import (
"TrangleAgent/internal/controller"
"TrangleAgent/internal/controller/websocket"
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcmd"
"leke/internal/controller"
"leke/internal/controller/websocket"
)
var (
@@ -17,9 +18,15 @@ var (
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
s := g.Server()
// ... existing code ...
// CORS 中间件
// CORS 中间件 - 排除 swagger 和 openapi 路径
s.Use(func(r *ghttp.Request) {
// 排除 swagger 相关路径
path := r.URL.Path
if path == "/swagger" || path == "/api.json" || path == "/swagger/" || path == "/api.json/" {
r.Middleware.Next()
return
}
r.Response.CORS(ghttp.CORSOptions{
AllowOrigin: "http://localhost:3000,http://localhost:8080",
AllowMethods: "GET,POST,PUT,DELETE,OPTIONS",
@@ -33,7 +40,6 @@ var (
}
r.Middleware.Next()
})
// ... existing code ...
// 注册 API 路由组
s.Group("/api", func(group *ghttp.RouterGroup) {
@@ -44,8 +50,7 @@ var (
// 注册 WebSocket 聊天室路由(不在 /api 组下,因为 WebSocket 不需要中间件)
s.BindHandler("/ws/chat", websocket.HandleChatConnections)
// 配置静态文件服务(用于提供 HTML 客户端页面)
s.SetServerRoot("resource/public")
s.SetDumpRouterMap(false)
s.Run()
return nil

View File

@@ -1,5 +1,4 @@
package consts
// 加盐
const Salt = "leke"
const qa_empathy, qa_presence, qa_initiative, qa_vigor, qa_tenacity = "empathy", "presence", "initiative", "vigor", "tenacity"
const Salt = "TrangleAgent"

View File

@@ -1,13 +1,13 @@
package controller
import (
"leke/internal/controller/containment"
"leke/internal/controller/department"
"leke/internal/controller/forum"
"leke/internal/controller/login"
"leke/internal/controller/room"
"leke/internal/controller/user"
"leke/internal/middleware"
"TrangleAgent/internal/controller/containment"
"TrangleAgent/internal/controller/department"
"TrangleAgent/internal/controller/forum"
"TrangleAgent/internal/controller/login"
"TrangleAgent/internal/controller/room"
"TrangleAgent/internal/controller/user"
"TrangleAgent/internal/middleware"
"github.com/gogf/gf/v2/net/ghttp"
)

View File

@@ -2,10 +2,10 @@ package containment
import (
"context"
"leke/api/containment"
"TrangleAgent/api/containment"
"leke/api/containment/v1"
"leke/internal/service"
"TrangleAgent/api/containment/v1"
"TrangleAgent/internal/service"
)
// ControllerV1 控制器结构体

View File

@@ -3,9 +3,9 @@ package department
import (
"context"
"leke/api/department"
v1 "leke/api/department/v1"
"leke/internal/service"
"TrangleAgent/api/department"
v1 "TrangleAgent/api/department/v1"
"TrangleAgent/internal/service"
)
type ControllerV1 struct{}

View File

@@ -2,8 +2,8 @@ package forum
import (
"context"
v1 "leke/api/forum/v1"
"leke/internal/service"
v1 "TrangleAgent/api/forum/v1"
"TrangleAgent/internal/service"
)
// ForumCommentsCreate 创建评论

View File

@@ -2,8 +2,8 @@ package forum
import (
"context"
v1 "leke/api/forum/v1"
"leke/internal/service"
v1 "TrangleAgent/api/forum/v1"
"TrangleAgent/internal/service"
)
type ControllerV1 struct{}

View File

@@ -3,9 +3,9 @@ package login
import (
"context"
"leke/api/login"
v1 "leke/api/login/v1"
"leke/internal/service"
"TrangleAgent/api/login"
v1 "TrangleAgent/api/login/v1"
"TrangleAgent/internal/service"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"

View File

@@ -2,9 +2,9 @@ package room
import (
"context"
"leke/api/room"
v1 "leke/api/room/v1"
"leke/internal/service"
"TrangleAgent/api/room"
v1 "TrangleAgent/api/room/v1"
"TrangleAgent/internal/service"
)
type ControllerV1 struct{}

View File

@@ -3,8 +3,8 @@ package user
import (
"context"
v1 "leke/api/user/v1"
"leke/internal/service"
v1 "TrangleAgent/api/user/v1"
"TrangleAgent/internal/service"
)
type RoleControllerV1 struct{}

View File

@@ -3,8 +3,8 @@ package user
import (
"context"
v1 "leke/api/user/v1"
"leke/internal/service"
v1 "TrangleAgent/api/user/v1"
"TrangleAgent/internal/service"
)
type ControllerV1 struct{}

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// coachesDao is the data access object for the table coaches.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// commentsDao is the data access object for the table comments.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// containmentRepoDao is the data access object for the table containment_repo.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// departmentDao is the data access object for the table department.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// fansDao is the data access object for the table fans.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// forumCommentsDao is the data access object for the table forum_comments.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// forumPostsDao is the data access object for the table forum_posts.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// groupClassEnrollmentsDao is the data access object for the table group_class_enrollments.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// groupClassesDao is the data access object for the table group_classes.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// roleCardsDao is the data access object for the table role_cards.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// subscribeDao is the data access object for the table subscribe.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// trpgRoomDao is the data access object for the table trpg_room.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// userDepartmentDao is the data access object for the table user_department.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// usersDao is the data access object for the table users.

View File

@@ -5,7 +5,7 @@
package dao
import (
"leke/internal/dao/internal"
"TrangleAgent/internal/dao/internal"
)
// workoutLogsDao is the data access object for the table workout_logs.

View File

@@ -5,10 +5,10 @@ import (
"errors"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"leke/api/forum/v1"
"leke/internal/dao"
"leke/internal/model/entity"
"leke/internal/service"
"TrangleAgent/api/forum/v1"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/model/entity"
"TrangleAgent/internal/service"
)
// ForumComments 评论相关方法

View File

@@ -3,10 +3,10 @@ package ForumComments
import (
"context"
"errors"
"leke/api/forum/v1"
"leke/internal/dao"
"leke/internal/model/entity"
"leke/internal/service"
"TrangleAgent/api/forum/v1"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/model/entity"
"TrangleAgent/internal/service"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"

View File

@@ -3,9 +3,9 @@ package containment
import (
"context"
"github.com/gogf/gf/v2/frame/g"
v1 "leke/api/containment/v1"
"leke/internal/model/response"
"leke/internal/service"
v1 "TrangleAgent/api/containment/v1"
"TrangleAgent/internal/model/response"
"TrangleAgent/internal/service"
)
type sContainment struct{}

View File

@@ -2,10 +2,10 @@ package department
import (
"context"
v1 "leke/api/department/v1"
"leke/internal/dao"
"leke/internal/model"
"leke/internal/service"
v1 "TrangleAgent/api/department/v1"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/model"
"TrangleAgent/internal/service"
)
type sDepartment struct{}

View File

@@ -4,9 +4,9 @@ import (
"context"
"github.com/gogf/gf/v2/os/gtime"
v1 "leke/api/user/v1"
"leke/internal/dao"
"leke/internal/service"
v1 "TrangleAgent/api/user/v1"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/service"
)
type sFans struct{}

View File

@@ -5,13 +5,13 @@
package logic
import (
_ "leke/internal/logic/ForumComments"
_ "leke/internal/logic/containment"
_ "leke/internal/logic/department"
_ "leke/internal/logic/fans"
_ "leke/internal/logic/login"
_ "leke/internal/logic/room"
_ "leke/internal/logic/subscribe"
_ "leke/internal/logic/trace"
_ "leke/internal/logic/user"
_ "TrangleAgent/internal/logic/ForumComments"
_ "TrangleAgent/internal/logic/containment"
_ "TrangleAgent/internal/logic/department"
_ "TrangleAgent/internal/logic/fans"
_ "TrangleAgent/internal/logic/login"
_ "TrangleAgent/internal/logic/room"
_ "TrangleAgent/internal/logic/subscribe"
_ "TrangleAgent/internal/logic/trace"
_ "TrangleAgent/internal/logic/user"
)

View File

@@ -6,12 +6,12 @@ import (
"database/sql"
"errors"
"fmt"
v1 "leke/api/login/v1"
"leke/internal/consts"
"leke/internal/dao"
"leke/internal/middleware"
"leke/internal/model"
"leke/internal/service"
v1 "TrangleAgent/api/login/v1"
"TrangleAgent/internal/consts"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/middleware"
"TrangleAgent/internal/model"
"TrangleAgent/internal/service"
"time"
"github.com/gogf/gf/v2/crypto/gmd5"

View File

@@ -2,11 +2,11 @@ package room
import (
"context"
v1 "leke/api/room/v1"
"leke/internal/dao"
"leke/internal/model"
"leke/internal/model/entity"
"leke/internal/service"
v1 "TrangleAgent/api/room/v1"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/model"
"TrangleAgent/internal/model/entity"
"TrangleAgent/internal/service"
)
type sRoom struct{}

View File

@@ -2,9 +2,9 @@ package subscribe
import (
"context"
v1 "leke/api/user/v1"
"leke/internal/dao"
"leke/internal/service"
v1 "TrangleAgent/api/user/v1"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/service"
"github.com/gogf/gf/v2/os/gtime"
)

View File

@@ -3,10 +3,10 @@ package trace
import (
"context"
"fmt"
v1 "leke/api/user/v1"
"leke/internal/dao"
"leke/internal/model/entity"
"leke/internal/service"
v1 "TrangleAgent/api/user/v1"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/model/entity"
"TrangleAgent/internal/service"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/os/gtime"

View File

@@ -2,11 +2,11 @@ package user
import (
"context"
v1 "leke/api/user/v1"
"leke/internal/dao"
"leke/internal/model"
"leke/internal/model/entity"
"leke/internal/service"
v1 "TrangleAgent/api/user/v1"
"TrangleAgent/internal/dao"
"TrangleAgent/internal/model"
"TrangleAgent/internal/model/entity"
"TrangleAgent/internal/service"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"

View File

@@ -19,7 +19,7 @@ const (
CtxUsername gctx.StrKey = "username"
// JwtSecretKey is the secret key for JWT signing and validation
// Note: In production, this should be replaced with a secure key
JwtSecretKey = "leke"
JwtSecretKey = "TrangleAgent"
)
// JWTAuth is a middleware that validates JWT tokens in the request header

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/containment/v1"
v1 "TrangleAgent/api/containment/v1"
)
type (

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/department/v1"
v1 "TrangleAgent/api/department/v1"
)
type (

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/user/v1"
v1 "TrangleAgent/api/user/v1"
)
type (

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/forum/v1"
v1 "TrangleAgent/api/forum/v1"
)
type (

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/login/v1"
v1 "TrangleAgent/api/login/v1"
)
type (

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/room/v1"
v1 "TrangleAgent/api/room/v1"
)
type (

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/user/v1"
v1 "TrangleAgent/api/user/v1"
)
type (

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/user/v1"
v1 "TrangleAgent/api/user/v1"
)
type (

View File

@@ -7,7 +7,7 @@ package service
import (
"context"
v1 "leke/api/user/v1"
v1 "TrangleAgent/api/user/v1"
)
type (

Binary file not shown.

View File

@@ -1,11 +1,11 @@
package main
import (
_ "leke/internal/packed"
_ "TrangleAgent/internal/packed"
_ "leke/internal/logic"
_ "TrangleAgent/internal/logic"
"leke/internal/cmd"
"TrangleAgent/internal/cmd"
_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
"github.com/gogf/gf/v2/os/gctx"

View File

@@ -1,227 +0,0 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<title>WebSocket 广播测试</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<style>
body {
padding: 20px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h2 {
color: #333;
margin-bottom: 20px;
}
#divShow {
max-height: 500px;
overflow-y: auto;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
background-color: #fafafa;
}
.client-info {
background-color: #e8f4f8;
padding: 8px;
margin-bottom: 10px;
border-radius: 4px;
font-size: 12px;
color: #666;
}
.message-item {
margin-bottom: 8px;
padding: 8px;
border-radius: 4px;
word-wrap: break-word;
}
.timestamp {
font-size: 11px;
color: #999;
margin-right: 10px;
}
.user-input {
margin-top: 15px;
}
.status-badge {
display: inline-block;
padding: 4px 8px;
border-radius: 3px;
font-size: 12px;
margin-left: 10px;
}
.status-connected {
background-color: #5cb85c;
color: white;
}
.status-disconnected {
background-color: #d9534f;
color: white;
}
</style>
</head>
<body>
<div class="container">
<h2>
WebSocket 广播测试
<span id="statusBadge" class="status-badge status-disconnected">未连接</span>
</h2>
<div class="client-info" id="clientInfo">
客户端ID: <span id="clientId"></span> | 连接状态: <span id="connectionStatus">等待连接...</span>
</div>
<div class="list-group" id="divShow"></div>
<div class="user-input">
<div class="input-group">
<input type="text" class="form-control" id="txtContent" autofocus placeholder="输入要广播的消息...">
<span class="input-group-btn">
<button class="btn btn-primary" id="btnSend">发送广播</button>
</span>
</div>
<small class="text-muted" style="display: block; margin-top: 10px;">
提示打开多个浏览器窗口或标签页在一个窗口中发送消息所有窗口都会收到广播消息
</small>
</div>
</div>
</body>
</html>
<script type="application/javascript">
// 生成客户端ID
const clientId = 'Client-' + Math.random().toString(36).substr(2, 9);
document.getElementById('clientId').textContent = clientId;
function showInfo(content) {
const timestamp = new Date().toLocaleTimeString();
const html = '<div class="list-group-item list-group-item-info message-item">' +
'<span class="timestamp">[' + timestamp + ']</span>' + content + '</div>';
$(html).appendTo("#divShow");
$("#divShow").scrollTop($("#divShow")[0].scrollHeight);
}
function showWarning(content) {
const timestamp = new Date().toLocaleTimeString();
const html = '<div class="list-group-item list-group-item-warning message-item">' +
'<span class="timestamp">[' + timestamp + ']</span>' + content + '</div>';
$(html).appendTo("#divShow");
$("#divShow").scrollTop($("#divShow")[0].scrollHeight);
}
function showSuccess(content) {
const timestamp = new Date().toLocaleTimeString();
const html = '<div class="list-group-item list-group-item-success message-item">' +
'<span class="timestamp">[' + timestamp + ']</span>' + content + '</div>';
$(html).appendTo("#divShow");
$("#divShow").scrollTop($("#divShow")[0].scrollHeight);
}
function showError(content) {
const timestamp = new Date().toLocaleTimeString();
const html = '<div class="list-group-item list-group-item-danger message-item">' +
'<span class="timestamp">[' + timestamp + ']</span>' + content + '</div>';
$(html).appendTo("#divShow");
$("#divShow").scrollTop($("#divShow")[0].scrollHeight);
}
function updateStatus(connected) {
const badge = $('#statusBadge');
const status = $('#connectionStatus');
if (connected) {
badge.removeClass('status-disconnected').addClass('status-connected').text('已连接');
status.text('已连接');
} else {
badge.removeClass('status-connected').addClass('status-disconnected').text('未连接');
status.text('未连接');
}
}
$(function () {
// 获取当前页面的协议和主机
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
const url = protocol + "//" + host + "/ws";
let ws = new WebSocket(url);
try {
// WebSocket 连接成功
ws.onopen = function () {
updateStatus(true);
showInfo("✅ WebSocket 服务器 [" + url + "] 连接成功客户端ID: " + clientId);
};
// WebSocket 连接关闭
ws.onclose = function () {
updateStatus(false);
if (ws) {
ws.close();
ws = null;
}
showError("❌ WebSocket 服务器 [" + url + "] 连接已关闭!");
};
// WebSocket 连接错误
ws.onerror = function () {
updateStatus(false);
if (ws) {
ws.close();
ws = null;
}
showError("❌ WebSocket 服务器 [" + url + "] 连接错误!");
};
// WebSocket 响应消息(接收广播)
ws.onmessage = function (event) {
try {
// 服务端使用 WriteJSON 发送,所以消息是 JSON 字符串
let message = event.data;
// 如果是 JSON 字符串,尝试解析
if (typeof message === 'string' && message.startsWith('"')) {
message = JSON.parse(message);
}
showWarning("📢 收到广播: " + message);
} catch (e) {
showWarning("📢 收到广播: " + event.data);
}
};
} catch (e) {
alert("连接错误: " + e.message);
}
// 点击发送消息
$("#btnSend").on("click", function () {
if (ws == null || ws.readyState !== WebSocket.OPEN) {
showError("WebSocket 服务器连接失败,请刷新页面!");
return;
}
const content = $.trim($("#txtContent").val());
if (content.length <= 0) {
alert("请输入要发送的内容!");
return;
}
// 发送 JSON 格式的消息(服务端使用 ReadJSON 读取)
try {
ws.send(JSON.stringify(content));
$("#txtContent").val("");
showSuccess("📤 发送广播: " + content);
} catch (e) {
showError("发送失败: " + e.message);
}
});
// 回车发送消息
$("#txtContent").on("keydown", function (event) {
if (event.keyCode === 13) {
$("#btnSend").trigger("click");
}
});
})
</script>

View File

@@ -1,359 +0,0 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<title>TrangleAgent - 聊天室测试</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<style>
body {
padding: 20px;
background-color: #f5f5f5;
}
.container {
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
max-width: 1200px;
margin: 0 auto;
}
h2 {
color: #333;
margin-bottom: 20px;
}
.chat-container {
display: flex;
gap: 20px;
margin-top: 20px;
}
.chat-messages {
flex: 1;
max-height: 500px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
padding: 15px;
background-color: #fafafa;
min-height: 400px;
}
.message-item {
margin-bottom: 12px;
padding: 10px;
border-radius: 4px;
word-wrap: break-word;
}
.message-own {
background-color: #d4edda;
border-left: 3px solid #28a745;
}
.message-other {
background-color: #fff3cd;
border-left: 3px solid #ffc107;
}
.message-system {
background-color: #e2e3e5;
border-left: 3px solid #6c757d;
font-style: italic;
}
.timestamp {
font-size: 11px;
color: #999;
margin-right: 10px;
}
.user-info {
font-weight: bold;
color: #007bff;
margin-right: 8px;
}
.room-info {
background-color: #e8f4f8;
padding: 15px;
margin-bottom: 20px;
border-radius: 4px;
}
.input-group {
margin-top: 15px;
}
.status-badge {
display: inline-block;
padding: 4px 8px;
border-radius: 3px;
font-size: 12px;
margin-left: 10px;
}
.status-connected {
background-color: #5cb85c;
color: white;
}
.status-disconnected {
background-color: #d9534f;
color: white;
}
.sidebar {
width: 250px;
}
.sidebar-card {
background-color: #f8f9fa;
padding: 15px;
border-radius: 4px;
margin-bottom: 15px;
}
</style>
</head>
<body>
<div class="container">
<h2>
TrangleAgent 聊天室测试
<span id="statusBadge" class="status-badge status-disconnected">未连接</span>
</h2>
<div class="room-info">
<div class="form-group">
<label>房间ID:</label>
<input type="text" class="form-control" id="roomId" value="room1" placeholder="输入房间ID">
</div>
<div class="form-group">
<label>用户ID:</label>
<input type="text" class="form-control" id="userId" value="" placeholder="输入用户ID留空自动生成">
</div>
<button class="btn btn-primary" id="btnConnect">连接聊天室</button>
<button class="btn btn-danger" id="btnDisconnect" disabled>断开连接</button>
</div>
<div class="chat-container">
<div class="chat-messages" id="chatMessages">
<div class="message-item message-system">
<span class="timestamp">[系统]</span>
等待连接到聊天室...
</div>
</div>
<div class="sidebar">
<div class="sidebar-card">
<h4>使用说明</h4>
<ul style="font-size: 12px; padding-left: 20px;">
<li>输入房间ID和用户ID</li>
<li>点击"连接聊天室"</li>
<li>打开多个窗口测试</li>
<li>在不同窗口发送消息</li>
<li>所有窗口都会收到广播</li>
</ul>
</div>
<div class="sidebar-card">
<h4>连接信息</h4>
<div id="connectionInfo" style="font-size: 12px;">
<div>状态: <span id="connStatus">未连接</span></div>
<div>房间: <span id="connRoom">-</span></div>
<div>用户: <span id="connUser">-</span></div>
</div>
</div>
</div>
</div>
<div class="input-group">
<input type="text" class="form-control" id="txtMessage" placeholder="输入消息..." disabled>
<span class="input-group-btn">
<button class="btn btn-primary" id="btnSend" disabled>发送</button>
</span>
</div>
</div>
</body>
</html>
<script type="application/javascript">
let ws = null;
let currentRoomId = '';
let currentUserId = '';
// 生成用户ID
function generateUserId() {
return 'User-' + Math.random().toString(36).substr(2, 9);
}
// 初始化用户ID
$(function() {
const userIdInput = $('#userId');
if (!userIdInput.val()) {
userIdInput.val(generateUserId());
}
});
function updateStatus(connected) {
const badge = $('#statusBadge');
const status = $('#connStatus');
if (connected) {
badge.removeClass('status-disconnected').addClass('status-connected').text('已连接');
status.text('已连接');
$('#btnConnect').prop('disabled', true);
$('#btnDisconnect').prop('disabled', false);
$('#txtMessage').prop('disabled', false);
$('#btnSend').prop('disabled', false);
} else {
badge.removeClass('status-connected').addClass('status-disconnected').text('未连接');
status.text('未连接');
$('#btnConnect').prop('disabled', false);
$('#btnDisconnect').prop('disabled', true);
$('#txtMessage').prop('disabled', true);
$('#btnSend').prop('disabled', true);
}
}
function addMessage(message, type, userId) {
const timestamp = new Date().toLocaleTimeString();
const messagesDiv = $('#chatMessages');
let messageClass = 'message-other';
let displayUserId = userId || '系统';
if (type === 'own') {
messageClass = 'message-own';
} else if (type === 'system') {
messageClass = 'message-system';
displayUserId = '系统';
}
const html = '<div class="message-item ' + messageClass + '">' +
'<span class="timestamp">[' + timestamp + ']</span>' +
'<span class="user-info">' + displayUserId + ':</span>' +
message +
'</div>';
messagesDiv.append(html);
messagesDiv.scrollTop(messagesDiv[0].scrollHeight);
}
function connect() {
const roomId = $('#roomId').val().trim();
const userId = $('#userId').val().trim() || generateUserId();
if (!roomId) {
alert('请输入房间ID');
return;
}
if (!userId) {
$('#userId').val(generateUserId());
return;
}
currentRoomId = roomId;
currentUserId = userId;
$('#connRoom').text(roomId);
$('#connUser').text(userId);
// 获取当前页面的协议和主机
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
const url = protocol + "//" + host + "/ws/chat?roomId=" + encodeURIComponent(roomId);
try {
ws = new WebSocket(url);
ws.onopen = function() {
updateStatus(true);
addMessage('成功连接到聊天室: ' + roomId, 'system');
// 发送加入消息
const joinMsg = {
roomId: roomId,
userId: userId,
message: userId + ' 加入了聊天室',
type: 'join'
};
ws.send(JSON.stringify(joinMsg));
};
ws.onclose = function() {
updateStatus(false);
addMessage('连接已断开', 'system');
ws = null;
};
ws.onerror = function() {
updateStatus(false);
addMessage('连接错误', 'system');
};
ws.onmessage = function(event) {
try {
// 解析收到的消息
const data = JSON.parse(event.data);
if (data.userId === currentUserId) {
addMessage(data.message, 'own', data.userId);
} else {
addMessage(data.message, 'other', data.userId);
}
} catch (e) {
// 如果不是JSON直接显示
addMessage(event.data, 'other');
}
};
} catch (e) {
alert('连接错误: ' + e.message);
}
}
function disconnect() {
if (ws) {
// 发送离开消息
const leaveMsg = {
roomId: currentRoomId,
userId: currentUserId,
message: currentUserId + ' 离开了聊天室',
type: 'leave'
};
try {
ws.send(JSON.stringify(leaveMsg));
} catch (e) {
console.error('发送离开消息失败:', e);
}
ws.close();
ws = null;
}
updateStatus(false);
addMessage('已断开连接', 'system');
}
function sendMessage() {
if (!ws || ws.readyState !== WebSocket.OPEN) {
alert('未连接到聊天室');
return;
}
const message = $('#txtMessage').val().trim();
if (!message) {
alert('请输入消息');
return;
}
const chatMsg = {
roomId: currentRoomId,
userId: currentUserId,
message: message,
type: 'message'
};
try {
ws.send(JSON.stringify(chatMsg));
$('#txtMessage').val('');
} catch (e) {
alert('发送失败: ' + e.message);
}
}
// 绑定事件
$(function() {
$('#btnConnect').on('click', connect);
$('#btnDisconnect').on('click', disconnect);
$('#btnSend').on('click', sendMessage);
$('#txtMessage').on('keydown', function(event) {
if (event.keyCode === 13) {
sendMessage();
}
});
});
</script>

View File

@@ -1,109 +0,0 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<title>GoFrame WebSocket Echo Server</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<style>
body {
padding: 20px;
}
#divShow {
max-height: 400px;
overflow-y: auto;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
<h2>GoFrame WebSocket Echo Server</h2>
<div class="list-group" id="divShow"></div>
<div>
<div><input class="form-control" id="txtContent" autofocus placeholder="输入要发送的内容..."></div>
<div><button class="btn btn-primary" id="btnSend" style="margin-top:15px">发送</button></div>
</div>
</div>
</body>
</html>
<script type="application/javascript">
function showInfo(content) {
$("<div class=\"list-group-item list-group-item-info\">" + content + "</div>").appendTo("#divShow")
$("#divShow").scrollTop($("#divShow")[0].scrollHeight);
}
function showWaring(content) {
$("<div class=\"list-group-item list-group-item-warning\">" + content + "</div>").appendTo("#divShow")
$("#divShow").scrollTop($("#divShow")[0].scrollHeight);
}
function showSuccess(content) {
$("<div class=\"list-group-item list-group-item-success\">" + content + "</div>").appendTo("#divShow")
$("#divShow").scrollTop($("#divShow")[0].scrollHeight);
}
function showError(content) {
$("<div class=\"list-group-item list-group-item-danger\">" + content + "</div>").appendTo("#divShow")
$("#divShow").scrollTop($("#divShow")[0].scrollHeight);
}
$(function () {
// 获取当前页面的协议和主机
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
const url = protocol + "//" + host + "/ws";
let ws = new WebSocket(url);
try {
// WebSocket 连接成功
ws.onopen = function () {
showInfo("WebSocket 服务器 [" + url + "] 连接成功!");
};
// WebSocket 连接关闭
ws.onclose = function () {
if (ws) {
ws.close();
ws = null;
}
showError("WebSocket 服务器 [" + url + "] 连接已关闭!");
};
// WebSocket 连接错误
ws.onerror = function () {
if (ws) {
ws.close();
ws = null;
}
showError("WebSocket 服务器 [" + url + "] 连接错误!");
};
// WebSocket 响应消息
ws.onmessage = function (result) {
showWaring(" > " + result.data);
};
} catch (e) {
alert(e.message);
}
// 点击发送消息
$("#btnSend").on("click", function () {
if (ws == null) {
showError("WebSocket 服务器 [" + url + "] 连接失败,请刷新页面!");
return;
}
const content = $.trim($("#txtContent").val()).replace(/[\n]/g, "");
if (content.length <= 0) {
alert("请输入要发送的内容!");
return;
}
$("#txtContent").val("")
showSuccess("发送: " + content);
ws.send(content);
});
// 回车发送消息
$("#txtContent").on("keydown", function (event) {
if (event.keyCode === 13) {
$("#btnSend").trigger("click");
}
});
})
</script>

View File

@@ -1,305 +0,0 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>三角机构 · 机密通行码</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
body {
margin: 0;
padding: 0;
background: #f5f5f7;
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",
Arial,"PingFang SC","Microsoft YaHei",sans-serif;
color: #1f2933;
}
.wrapper {
padding: 32px 12px;
}
.window {
max-width: 560px;
margin: 0 auto;
background: #ffffff;
border-radius: 14px;
box-shadow:
0 20px 40px rgba(0,0,0,.16),
0 0 0 3px #111827;
overflow: hidden;
position: relative;
}
.window::before {
/* 顶部“打印残影”质感 */
content: "";
position: absolute;
left: 0;
right: 0;
top: -18px;
height: 18px;
background: repeating-linear-gradient(
90deg,
rgba(15,23,42,.12) 0,
rgba(15,23,42,.12) 24px,
transparent 24px,
transparent 48px
);
opacity: .7;
}
.window-header {
background: #f3f4f6;
border-bottom: 1px solid #d1d5db;
padding: 8px 14px;
display: flex;
align-items: center;
justify-content: space-between;
}
.title-left {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
letter-spacing: .12em;
text-transform: uppercase;
color: #4b5563;
}
.title-icon {
width: 20px;
height: 20px;
border-radius: 6px;
background: #b91c1c;
display: flex;
align-items: center;
justify-content: center;
}
.title-icon-inner {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 8px solid #f9fafb;
}
.title-right {
font-size: 12px;
color: #9ca3af;
}
.window-body {
padding: 24px 24px 20px;
}
.logo-block {
text-align: center;
margin-bottom: 18px;
}
.logo-main {
font-size: 22px;
font-weight: 800;
letter-spacing: .18em;
color: #111827;
}
.logo-main span {
color: #b91c1c;
}
.logo-sub {
margin-top: 4px;
font-size: 12px;
color: #6b7280;
}
.alert-banner {
margin: 4px 0 18px;
padding: 10px 14px;
border-radius: 10px;
background: #fee2e2;
border: 1px solid #b91c1c;
color: #7f1d1d;
font-size: 13px;
font-weight: 600;
display: flex;
align-items: center;
gap: 8px;
}
.alert-badge {
width: 20px;
height: 20px;
border-radius: 999px;
background: #b91c1c;
color: #f9fafb;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.headline {
font-size: 18px;
font-weight: 800;
color: #b91c1c;
text-align: center;
margin: 4px 0 10px;
}
.headline-sub {
font-size: 13px;
color: #4b5563;
text-align: center;
margin-bottom: 18px;
}
.code-panel {
margin: 0 auto 20px;
max-width: 340px;
background: #111827;
border-radius: 16px;
padding: 16px 14px 18px;
box-shadow:
0 0 0 2px #b91c1c,
0 14px 26px rgba(0,0,0,.45);
text-align: center;
color: #e5e7eb;
position: relative;
overflow: hidden;
}
.code-panel::before {
content: "";
position: absolute;
inset: -30%;
background:
radial-gradient(circle at 0% 0%, rgba(248,113,113,.35), transparent 60%),
radial-gradient(circle at 100% 100%, rgba(239,68,68,.22), transparent 60%);
opacity: .9;
mix-blend-mode: screen;
}
.code-label {
position: relative;
font-size: 11px;
letter-spacing: .24em;
text-transform: uppercase;
color: #9ca3af;
margin-bottom: 4px;
}
.code-value {
position: relative;
font-size: 30px;
font-weight: 900;
letter-spacing: .3em;
color: #fef2f2;
text-shadow:
0 0 10px rgba(248,113,113,.95),
0 0 24px rgba(248,113,113,.85);
}
.code-meta {
position: relative;
margin-top: 10px;
font-size: 11px;
color: #e5e7eb;
opacity: .9;
}
.code-meta span {
color: #f97373;
}
.text-block {
font-size: 13px;
line-height: 1.7;
color: #4b5563;
margin-bottom: 14px;
}
.text-block strong {
color: #b91c1c;
}
.punish {
font-size: 13px;
line-height: 1.7;
color: #111827;
background: #fef2f2;
border-radius: 10px;
border: 1px dashed #b91c1c;
padding: 10px 12px;
margin-bottom: 14px;
}
.punish span {
color: #b91c1c;
font-weight: 700;
}
.footer {
margin-top: 4px;
font-size: 11px;
color: #9ca3af;
text-align: right;
}
.footer span {
color: #b91c1c;
font-weight: 600;
}
@media (max-width: 520px) {
.window {
margin: 0 4px;
}
.code-value {
font-size: 24px;
letter-spacing: .22em;
}
}
</style>
</head>
<body>
<div class="wrapper">
<div class="window">
<div class="window-header">
<div class="title-left">
<div class="title-icon">
<div class="title-icon-inner"></div>
</div>
<span>TRIANGLE AGENCY · INTERNAL</span>
</div>
<div class="title-right">ACCESS&nbsp;LEVEL: REDACTED</div>
</div>
<div class="window-body">
<div class="logo-block">
<div class="logo-main">
TRI<span></span>NGLE&nbsp;AG<span></span>NCY
</div>
<div class="logo-sub">三角机构 · 机密通信单</div>
</div>
<div class="alert-banner">
<div class="alert-badge">!</div>
<div>此邮件包含<span>机密通行密码</span>仅限机构内部人员查阅</div>
</div>
<div class="headline">内部通行码 · 请勿外传</div>
<div class="headline-sub">
下方代码用于解锁指定散逸端终端请在系统提示时准确输入
</div>
<div class="code-panel">
<div class="code-label">CONTAINMENT ACCESS CODE</div>
<div class="code-value">{{.Code}}</div>
<div class="code-meta">
有效期<span>5 分钟</span> · 失效后请向直属经理申请新码
</div>
</div>
<div class="text-block">
使用前请再次确认
<br>· 您正在使用的是<span>机构提供的终端或安全网络环境</span>
<br>· 周围无未授权人员屏幕不可被旁人窥视
<br>· 本通行码只用于当前任务不得截图转发或长期存储
</div>
<div class="punish">
如将本通行码<span>泄露给三角机构外部人员</span>
或被系统判定存在高风险共享行为
您将被立即要求前往<span>经理办公室</span>领取
<span>1 次申戒</span>并记录在个人档案中
</div>
<div class="text-block">
若您认为本邮件系误发或内容与任务不符请立即与上级经理或风控部门联系
并在完成报告前<span>不要尝试使用该通行码</span>
</div>
<div class="footer">
发件单位<span>三角机构 · 机密通讯科</span><br>
此邮件由系统自动发送请勿直接回复
</div>
</div>
</div>
</div>
</body>
</html>

View File

@@ -1,61 +0,0 @@
package ws
import (
"encoding/json"
chatmodel "leke/ws/model"
"github.com/gogf/gf/v2/net/ghttp"
)
// Client 表示一个在线用户的 WebSocket 连接
// 这里只是框架:先把字段和发送逻辑搭好,读写循环可以后面慢慢加。
type Client struct {
UserId uint64 // 当前用户ID
Nickname string // 昵称(可选)
Conn *ghttp.Request // 底层 WebSocket 连接
// Send 是一个发送队列:其他地方往这里丢 []byte这个 client 的写协程负责发出去
Send chan []byte
// Rooms 记录当前用户加入的房间(简单用 map 做集合)
Rooms map[string]bool
}
// NewClient 创建一个新的客户端连接对象
func NewClient(userId uint64, nickname string, conn *ghttp.Request) *Client {
return &Client{
UserId: userId,
Nickname: nickname,
Conn: conn,
Send: make(chan []byte, 256), // 简单先给一个缓冲,防止轻微阻塞
Rooms: make(map[string]bool),
}
}
// EnqueueMessage 将 ChatMessage 编码为 JSON 丢到 Send 队列
// 真正 WriteMessage 的动作建议在一个单独的 writeLoop 里做。
func (c *Client) EnqueueMessage(msg *chatmodel.ChatMessage) error {
// 如果需要,补一些默认字段
if msg.FromUserId == 0 {
msg.FromUserId = c.UserId
}
if msg.FromNickname == "" {
msg.FromNickname = c.Nickname
}
data, err := json.Marshal(msg)
if err != nil {
return err
}
select {
case c.Send <- data:
// 正常入队
default:
// 队列满了,可以考虑:丢弃 / 断开连接 / 打日志
// 这里简单选择丢弃,并返回错误
return ErrSendQueueFull
}
return nil
}

View File

@@ -1,26 +0,0 @@
### ChatMessage (服务端 客户端)
```json
{
"type": "world | room | private | system",
"subType": "message | user_join | user_leave | room_created",
"fromUserId": 123,
"fromNickname": "某某",
"roomId": "xxx",
"content": "xxx",
"time": "2025-12-08T12:34:56"
}
**这里的“放在哪里”** 👉 放在你的项目文档里,用来说明“聊天协议”。
---
## 总结一句人话版
这个 JSON **不是一个要单独存起来的文件**,而是你聊天系统里「**一条消息长什么样**」的**约定**
- 在前端:定义成一个 TypeScript interface / JSDoc 类型,用来写 WebSocket 的 `send``onmessage`
- 在后端:定义成一个 Go struct用来 `json.Unmarshal` / `json.Marshal`
- 在文档写在一个协议文档里提醒自己和队友所有聊天消息都按这个格式来
你下一步如果愿意我可以帮你把前端消息类型定义 + 后端 struct + 一条从前端发到后端再广播出去的完整流程图给你画成一个数据流思路方便你对着实现

View File

@@ -1,7 +0,0 @@
package ws
import "errors"
var (
ErrSendQueueFull = errors.New("客户端队列堵塞")
)

View File

@@ -1,132 +0,0 @@
package ws
import (
"sync"
chatmodel "leke/ws/model" // 按实际路径修改
)
// Hub 聊天中枢:管理所有连接和房间
type Hub struct {
mu sync.RWMutex
// 所有在线用户userId -> Client
clients map[uint64]*Client
// 房间成员roomId -> (userId -> Client)
rooms map[string]map[uint64]*Client
}
// 全局唯一 Hub简单起见用一个全局变量
var ChatHub = NewHub()
// NewHub 创建一个新的 Hub 实例
func NewHub() *Hub {
return &Hub{
clients: make(map[uint64]*Client),
rooms: make(map[string]map[uint64]*Client),
}
}
// Register 注册新连接
func (h *Hub) Register(c *Client) {
h.mu.Lock()
defer h.mu.Unlock()
h.clients[c.UserId] = c
// 默认认为所有在线用户都在世界频道,这里你可以根据需要扩展
}
// Unregister 移除连接(断线/退出)
func (h *Hub) Unregister(c *Client) {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.clients, c.UserId)
// 同时把他从所有房间移除
for roomId, members := range h.rooms {
if _, ok := members[c.UserId]; ok {
delete(members, c.UserId)
if len(members) == 0 {
delete(h.rooms, roomId)
}
}
}
}
// JoinRoom 加入房间
func (h *Hub) JoinRoom(userId uint64, roomId string) {
h.mu.Lock()
defer h.mu.Unlock()
client, ok := h.clients[userId]
if !ok {
return
}
members, ok := h.rooms[roomId]
if !ok {
members = make(map[uint64]*Client)
h.rooms[roomId] = members
}
members[userId] = client
client.Rooms[roomId] = true
}
// LeaveRoom 离开房间
func (h *Hub) LeaveRoom(userId uint64, roomId string) {
h.mu.Lock()
defer h.mu.Unlock()
client, ok := h.clients[userId]
if !ok {
return
}
if members, ok := h.rooms[roomId]; ok {
delete(members, userId)
if len(members) == 0 {
delete(h.rooms, roomId)
}
}
delete(client.Rooms, roomId)
}
// BroadcastWorld 向所有在线用户发送世界频道消息
func (h *Hub) BroadcastWorld(msg *chatmodel.ChatMessage) {
h.mu.RLock()
defer h.mu.RUnlock()
for _, client := range h.clients {
_ = client.EnqueueMessage(msg)
}
}
// BroadcastRoom 向房间内所有用户发送消息
func (h *Hub) BroadcastRoom(roomId string, msg *chatmodel.ChatMessage) {
h.mu.RLock()
defer h.mu.RUnlock()
members, ok := h.rooms[roomId]
if !ok {
return
}
for _, client := range members {
_ = client.EnqueueMessage(msg)
}
}
// SendPrivate 发送私聊消息
func (h *Hub) SendPrivate(fromUserId, toUserId uint64, msg *chatmodel.ChatMessage) {
h.mu.RLock()
defer h.mu.RUnlock()
toClient, ok := h.clients[toUserId]
if !ok {
return // 对方不在线可以后面扩展离线消息存DB
}
msg.FromUserId = fromUserId
_ = toClient.EnqueueMessage(msg)
}

View File

@@ -1,34 +0,0 @@
package model
// MessageType 消息的大类:发到哪里
type MessageType string
const (
TypeWorld MessageType = "world" // 世界频道
TypeRoom MessageType = "room" // 房间
TypePrivate MessageType = "private" // 私聊
TypeSystem MessageType = "system" // 系统消息(如通知、提示等)
)
// MessageAction 消息的动作:干什么事
type MessageAction string
const (
ActionSend MessageAction = "send" // 发送聊天消息
ActionJoinRoom MessageAction = "join_room" // 加入房间
ActionLeaveRoom MessageAction = "leave_room" // 离开房间
ActionCreateRoom MessageAction = "create_room" // 创建房间(也可以走 HTTP
)
// ChatMessage WebSocket 收/发的统一结构
// 前端和后端都按这个结构来编码/解码 JSON。
type ChatMessage struct {
Type MessageType `json:"type"` // 消息类型world/room/private/system
Action MessageAction `json:"action"` // 动作send/join_room/leave_room...
FromUserId uint64 `json:"fromUserId,omitempty"` // 发送者用户ID
FromNickname string `json:"fromNickname,omitempty"` // 发送者昵称
RoomId string `json:"roomId,omitempty"` // 房间ID房间消息时使用
ToUserId uint64 `json:"toUserId,omitempty"` // 目标用户ID私聊时使用
Content string `json:"content,omitempty"` // 文本内容
Time string `json:"time,omitempty"` // 时间ISO字符串前期用 string 即可)
}

32
Frontend/.gitignore vendored
View File

@@ -1,14 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
.DS_Store
*.log
.vscode
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3
Frontend/.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

View File

@@ -1,142 +0,0 @@
# 快速开始指南
## 安装和运行
1. **安装依赖**
```bash
npm install
```
2. **启动开发服务器**
```bash
npm run dev
```
3. **访问应用**
浏览器会自动打开 http://localhost:3000
## 使用流程
### 第一步:注册账号
1. 访问登录页面,点击"还没有账号?立即注册"
2. 填写账号、密码、确认密码和姓名
3. 点击注册,自动登录并跳转到主页
### 第二步:创建或加入房间
**创建房间:**
1. 在主页"创建房间"卡片中,输入房间名称
2. 点击"创建房间"按钮
3. 自动进入房间,成为主持人
**加入房间:**
1. 在主页"加入房间"卡片中,输入房间号
2. 点击"加入房间"按钮
3. 自动进入房间,成为玩家
### 第三步:使用骰子系统
**玩家初始投掷4个D4**
1. 进入房间后,玩家会看到"玩家初始投掷4个D4"区域
2. 点击"投掷4个D4"按钮
3. 查看投掷结果显示4个骰子的值
4. 如果3的数量少于3个
- 可以输入消耗的属性值来增加3的数量
- 如果最终达到3个3不会产生混沌值
- 否则每个不是3的D4会产生1点混沌值
5. 点击"确认投掷结果"完成初始投掷
**普通投掷:**
- 在"选择骰子类型"区域点击对应的骰子按钮D3/D4/D6/D12/D20
- 投掷结果会显示在投掷历史中
**混沌值管理(仅主持人):**
- 混沌值显示在页面顶部,所有人可见
- 主持人可以点击"消耗混沌值"按钮来消耗混沌值
### 第四步:总部/分部管理
1. 在主页点击"总部/分部管理"
2. **创建分部**(需要经理权限):
- 点击"创建分部"按钮
- 填写分部名称和负责人
- 点击确定
3. **发布招聘信息**(需要经理权限):
- 在右侧"招聘信息"卡片中,点击"发布招聘"
- 填写标题和内容
- 点击确定
4. **查看分部信息**
- 点击分部列表中的"查看详情"
- 可以看到该分部的天气、散一端等信息
### 第五步:异常管理
1. 在主页点击"异常管理"
2. **添加异常**
- 点击"添加异常"按钮
- 填写异常信息:
- 异常名称
- 类型(实体/概念/地点/现象)
- 特殊能力
- 焦点
- 领域(现实/记忆/时间/空间/生命/死亡/知识/情感)
- 点击确定
3. **收容异常**
- 在"未收容异常"列表中,点击"收容"按钮
- 异常会移动到"已收容异常"列表
4. **解决异常**
- 在"已收容异常"列表中,点击"标记为已解决"
- 异常会移动到"已解决异常"列表
5. **设置天气**
- 在"天气系统"卡片中,输入天气信息
- 点击"设置天气"按钮
## 功能说明
### 混沌值规则TRTC三角洲机构规则
1. **初始投掷规则**
- 玩家开始时必须投掷4个D4
- 如果投出的4个D4中3的数量达到3个可通过消耗属性值达到则不会产生混沌值
- 如果3的数量少于3个每个不是3的D4会产生1点混沌值
2. **混沌值显示**
- 混沌值显示在房间页面顶部,所有玩家可见
- 只有主持人可以消耗混沌值
3. **普通投掷**
- 普通投掷不会自动产生混沌值(除非特殊规则)
### 数据存储
- 当前版本使用浏览器的localStorage进行数据存储
- 所有数据保存在本地浏览器中
- 刷新页面后数据会保留
- 清除浏览器数据会丢失所有信息
## 注意事项
1. **房间号分享**:创建房间后,可以点击"复制房间号"按钮分享给其他玩家
2. **角色权限**
- 主持人:可以消耗混沌值
- 玩家:可以投掷骰子,但不能消耗混沌值
- 经理:可以创建分部、发布招聘信息
3. **数据同步**:当前版本是纯前端应用,多个浏览器标签页之间的数据不会实时同步
## 常见问题
**Q: 如何切换账号?**
A: 点击右上角"退出"按钮,然后使用其他账号登录。
**Q: 房间数据会丢失吗?**
A: 数据保存在浏览器localStorage中除非清除浏览器数据否则不会丢失。
**Q: 可以多人同时使用吗?**
A: 当前版本是纯前端多人使用时需要各自在浏览器中操作数据不会实时同步。如需实时同步需要集成WebSocket或后端API。

View File

@@ -1,140 +1,5 @@
# 三角洲机构 - TRPG跑团在线工具
# Vue 3 + Vite
基于Vue3 + Ant Design Vue构建的TRPG跑团在线工具网站遵循TRTC三角洲机构规则。
## 功能特性
### 用户系统
- 用户注册/登录(账号、密码、姓名)
- 用户信息管理
### 房间系统
- 创建房间,房间号可分享
- 加入房间(通过房间号)
- 房间内角色主持人Host和玩家PL
- 房间信息展示
### 骰子系统
- 支持常见骰子D3、D4、D6、D12、D20
- 玩家初始投掷4个D4
- **混沌值机制**
- 每个不是3的D4给主持人加1点混沌值
- 玩家投出3个3可通过消耗属性值达到不会产生混沌值
- 每个不是3的骰子都会变成混沌值
- 混沌值所有人可见
- 主持人可以消耗混沌值
- 投掷历史记录
### 总部/分部管理系统
- 创建分部
- 解散分部
- 发布招聘信息(经理权限)
- 查看招聘信息(所有分部成员)
- 分部信息管理(散一端、天气系统)
### 异常管理系统
- 添加异常(名称、类型、特殊能力、焦点、领域)
- 异常收容
- 异常解决
- 异常分类:未收容、已收容、已解决
- 天气系统设置
- 散一端管理
## 技术栈
- Vue 3 (Composition API)
- Ant Design Vue 4.x
- Vue Router 4
- Pinia (状态管理)
- Vite (构建工具)
## 项目结构
```
src/
├── views/ # 页面组件
│ ├── Login.vue # 登录页
│ ├── Register.vue # 注册页
│ ├── Home.vue # 主页
│ ├── Room.vue # 房间页
│ ├── Organization.vue # 总部/分部管理
│ └── Anomaly.vue # 异常管理
├── stores/ # Pinia状态管理
│ ├── user.js # 用户状态
│ ├── room.js # 房间状态
│ ├── organization.js # 组织状态
│ └── anomaly.js # 异常状态
├── router/ # 路由配置
├── utils/ # 工具函数
└── main.js # 入口文件
```
## 快速开始
### 安装依赖
```bash
npm install
```
### 开发运行
```bash
npm run dev
```
访问 http://localhost:3000
### 构建生产版本
```bash
npm run build
```
## 使用说明
### 1. 注册/登录
- 首次使用需要注册账号(账号、密码、姓名)
- 注册成功后自动登录
### 2. 创建/加入房间
- 在主页可以创建新房间或通过房间号加入现有房间
- 创建房间后自动成为主持人
- 房间号可以分享给其他玩家
### 3. 使用骰子系统
- **玩家初始投掷**进入房间后玩家可以投掷4个D4
- **混沌值规则**
- 如果投出的4个D4中3的数量少于3个会产生混沌值
- 玩家可以通过消耗属性值来增加3的数量
- 如果最终达到3个3则不会产生混沌值
- 每个不是3的D4会产生1点混沌值
- **普通投掷**可以选择D3/D4/D6/D12/D20进行投掷
- **消耗混沌值**:只有主持人可以消耗混沌值
### 4. 总部/分部管理
- 经理可以创建分部、发布招聘信息
- 所有成员可以查看招聘信息
- 每个分部可以设置天气和散一端
### 5. 异常管理
- 添加异常时需要填写:名称、类型、特殊能力、焦点、领域
- 异常类型:实体、概念、地点、现象
- 异常领域:现实、记忆、时间、空间、生命、死亡、知识、情感
- 异常状态流转:未收容 → 已收容 → 已解决
## 注意事项
- 当前版本使用localStorage进行数据存储纯前端
- 刷新页面后数据会保留
- 如需后端支持需要对接相应的API接口
## 开发计划
- [ ] WebSocket实时通信
- [ ] 后端API集成
- [ ] 数据持久化
- [ ] 更多骰子类型和规则
- [ ] 角色属性管理
- [ ] 跑团记录导出
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about IDE Support for Vue in the [Vue Docs Scaling up Guide](https://vuejs.org/guide/scaling-up/tooling.html#ide-support).

View File

@@ -0,0 +1,10 @@
import request from "../../src/api/http.js";
import { type LoginResponse, type DeepRequired, type LoginRequest } from "../../interface";
import { type AxiosRequestConfig } from "axios";
/**
* /api/auth/login
*/
export function postApiAuthLogin(input: LoginRequest, config?: AxiosRequestConfig) {
return request.post<DeepRequired<LoginResponse>>(`/api/auth/login`, input, config);
}

View File

@@ -0,0 +1,10 @@
import request from "../../src/api/http.js";
import { type ApiResponse, type DeepRequired } from "../../interface";
import { type AxiosRequestConfig } from "axios";
/**
* /api/auth/logout
*/
export function postApiAuthLogout(config?: AxiosRequestConfig) {
return request.post<DeepRequired<ApiResponse>>(`/api/auth/logout`, config);
}

122
Frontend/docs.json Normal file
View File

@@ -0,0 +1,122 @@
{
"openapi": "3.0.1",
"info": {
"title": "TrangleAgent API",
"description": "TrangleAgent API Documentation",
"version": "v1"
},
"servers": [
{
"url": "http://localhost:8080",
"description": "Generated server url"
}
],
"paths": {
"/api/auth/login": {
"post": {
"tags": [
"auth-controller"
],
"operationId": "login",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/LoginRequest"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/LoginResponse"
}
}
}
}
}
}
},
"/api/auth/logout": {
"post": {
"tags": [
"auth-controller"
],
"operationId": "logout",
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ApiResponse"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"LoginRequest": {
"type": "object",
"properties": {
"username": {
"type": "string"
},
"password": {
"type": "string"
}
}
},
"LoginResponse": {
"type": "object",
"properties": {
"token": {
"type": "string"
},
"user": {
"$ref": "#/components/schemas/User"
}
}
},
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"username": {
"type": "string"
},
"email": {
"type": "string"
}
}
},
"ApiResponse": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
},
"data": {
"type": "object"
}
}
}
}
}
}

View File

@@ -1,21 +1,13 @@
<!DOCTYPE html>
<html lang="zh-CN">
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>三角洲机构 - TRPG跑团工具</title>
<title>trangleagent</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -1,32 +1,23 @@
{
"name": "trangle-agent",
"version": "1.0.0",
"description": "TRPG跑团在线工具网站 - 三角洲机构",
"name": "trangleagent",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
"preview": "vite preview",
"swagger:generate": "zerone api -p ./src/api"
},
"dependencies": {
"vue": "^3.4.21",
"vue-router": "^4.3.0",
"pinia": "^2.1.7",
"ant-design-vue": "^4.2.1",
"@ant-design/icons-vue": "^7.0.1",
"axios": "^1.6.7"
"ant-design-vue": "^4.2.6",
"axios": "^1.7.9",
"vue": "^3.5.24",
"vue-router": "^4.4.5"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.0.4",
"vite": "^5.1.4",
"sass": "^1.71.1"
"@vitejs/plugin-vue": "^6.0.1",
"vite": "^7.2.4"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 462 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 579 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 449 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 669 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 527 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 534 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 538 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 608 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 714 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 462 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 653 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 509 KiB

Some files were not shown because too many files have changed in this diff Show More