MCPcopy
hub / github.com/kingwrcy/moments / AddComment

Method AddComment

backend/handler/comment.go:122–214  ·  view source on GitHub ↗

AddComment godoc @Tags Comment @Summary 添加评论 @Accept json @Produce json @Param object body vo.AddCommentReq true "添加评论" @Success 200 @Router /api/comment/add [post]

(ctx echo.Context)

Source from the content-addressed store, hash-verified

120// @Success 200
121// @Router /api/comment/add [post]
122func (c CommentHandler) AddComment(ctx echo.Context) error {
123 var (
124 req vo.AddCommentReq
125 comment db.Comment
126 now = time.Now()
127 sysConfig db.SysConfig
128 sysConfigVO vo.FullSysConfigVO
129 )
130 err := ctx.Bind(&req)
131 if err != nil {
132 c.base.log.Error().Msgf("发表评论时参数校验失败,原因:%s", err)
133 return FailResp(ctx, ParamError)
134 }
135 c.base.db.First(&sysConfig)
136 _ = json.Unmarshal([]byte(sysConfig.Content), &sysConfigVO)
137
138 if !sysConfigVO.EnableComment {
139 return FailRespWithMsg(ctx, Fail, "评论未开启")
140 }
141
142 if err := checkGoogleRecaptcha(c.base.log, sysConfigVO, req.Token); err != nil {
143 return FailRespWithMsg(ctx, Fail, err.Error())
144 }
145 if context, ok := ctx.(CustomContext); ok {
146 currentUser := context.CurrentUser()
147 if currentUser == nil {
148 comment.Username = req.Username
149 comment.Email = req.Email
150 } else {
151 comment.Username = currentUser.Nickname
152 comment.Email = currentUser.Email
153 comment.Author = fmt.Sprintf("%d", currentUser.Id)
154 }
155 }
156
157 if comment.Username == "" {
158 // 尝试从 Cookie 中获取用户名
159 cookie, err := ctx.Cookie("anonymous_username")
160 var username string
161
162 if err != nil || cookie.Value == "" {
163 // 如果 Cookie 不存在,生成一个新的随机用户名
164 username = fmt.Sprintf("匿名用户_%s", uuid.New().String()[:4])
165 // 对用户名进行 URL 编码
166 encodedUsername := url.QueryEscape(username)
167 // 设置 Cookie,有效期 7 天
168 ctx.SetCookie(&http.Cookie{
169 Name: "anonymous_username",
170 Value: encodedUsername,
171 Path: "/",
172 Expires: time.Now().Add(7 * 24 * time.Hour),
173 })
174 } else {
175 // 如果 Cookie 存在,使用之前的用户名
176 decodedUsername, err := url.QueryUnescape(cookie.Value)
177 if err != nil {
178 // 生成一个新的随机用户名
179 username = fmt.Sprintf("匿名用户_%s", uuid.New().String()[:4])

Callers

nothing calls this directly

Calls 7

FailRespFunction · 0.85
FailRespWithMsgFunction · 0.85
checkGoogleRecaptchaFunction · 0.85
SuccessRespFunction · 0.85
ErrorMethod · 0.80
CurrentUserMethod · 0.80

Tested by

no test coverage detected