@@ -4,17 +4,19 @@ import (
4
4
"encoding/json"
5
5
"errors"
6
6
"fmt"
7
+ "io"
8
+ "net/http"
9
+ "net/url"
10
+ "strconv"
11
+ "time"
12
+
13
+ "github.com/google/uuid"
7
14
"github.com/kingwrcy/moments/db"
8
15
"github.com/kingwrcy/moments/vo"
9
16
"github.com/labstack/echo/v4"
10
17
"github.com/rs/zerolog"
11
18
"github.com/samber/do/v2"
12
19
"gorm.io/gorm"
13
- "io"
14
- "net/http"
15
- "net/url"
16
- "strconv"
17
- "time"
18
20
)
19
21
20
22
type CommentHandler struct {
@@ -147,6 +149,45 @@ func (c CommentHandler) AddComment(ctx echo.Context) error {
147
149
}
148
150
}
149
151
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
+
150
191
comment .Content = req .Content
151
192
comment .Email = req .Email
152
193
comment .CreatedAt = & now
0 commit comments