Skip to content

Commit c084a0e

Browse files
authored
Merge pull request #261 from Jinvic/dev
fix: 无法回复无用户名的评论
2 parents 676ce4c + bb36a25 commit c084a0e

File tree

1 file changed

+46
-5
lines changed

1 file changed

+46
-5
lines changed

backend/handler/comment.go

+46-5
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,19 @@ import (
44
"encoding/json"
55
"errors"
66
"fmt"
7+
"io"
8+
"net/http"
9+
"net/url"
10+
"strconv"
11+
"time"
12+
13+
"github.com/google/uuid"
714
"github.com/kingwrcy/moments/db"
815
"github.com/kingwrcy/moments/vo"
916
"github.com/labstack/echo/v4"
1017
"github.com/rs/zerolog"
1118
"github.com/samber/do/v2"
1219
"gorm.io/gorm"
13-
"io"
14-
"net/http"
15-
"net/url"
16-
"strconv"
17-
"time"
1820
)
1921

2022
type CommentHandler struct {
@@ -147,6 +149,45 @@ func (c CommentHandler) AddComment(ctx echo.Context) error {
147149
}
148150
}
149151

152+
if comment.Username == "" {
153+
// 尝试从 Cookie 中获取用户名
154+
cookie, err := ctx.Cookie("anonymous_username")
155+
var username string
156+
157+
if err != nil || cookie.Value == "" {
158+
// 如果 Cookie 不存在,生成一个新的随机用户名
159+
username = fmt.Sprintf("匿名用户_%s", uuid.New().String()[:4])
160+
// 对用户名进行 URL 编码
161+
encodedUsername := url.QueryEscape(username)
162+
// 设置 Cookie,有效期 7 天
163+
ctx.SetCookie(&http.Cookie{
164+
Name: "anonymous_username",
165+
Value: encodedUsername,
166+
Path: "/",
167+
Expires: time.Now().Add(7 * 24 * time.Hour),
168+
})
169+
} else {
170+
// 如果 Cookie 存在,使用之前的用户名
171+
decodedUsername, err := url.QueryUnescape(cookie.Value)
172+
if err != nil {
173+
// 生成一个新的随机用户名
174+
username = fmt.Sprintf("匿名用户_%s", uuid.New().String()[:4])
175+
// 对用户名进行 URL 编码
176+
encodedUsername := url.QueryEscape(username)
177+
// 设置 Cookie,有效期 7 天
178+
ctx.SetCookie(&http.Cookie{
179+
Name: "anonymous_username",
180+
Value: encodedUsername,
181+
Path: "/",
182+
Expires: time.Now().Add(7 * 24 * time.Hour),
183+
})
184+
} else {
185+
username = decodedUsername
186+
}
187+
}
188+
comment.Username = username
189+
}
190+
150191
comment.Content = req.Content
151192
comment.Email = req.Email
152193
comment.CreatedAt = &now

0 commit comments

Comments
 (0)