add:生成短链支持自定义id

This commit is contained in:
hz
2025-03-07 17:30:28 +08:00
parent b57e4cf49f
commit cc0b73d7a4
4 changed files with 73 additions and 14 deletions

View File

@ -32,10 +32,27 @@ func GenerateLinkHandler(c *gin.Context) {
return
}
hash, err := generateUniqueHash()
if err != nil {
respondWithError(c, http.StatusInternalServerError, "生成短链接失败")
return
var hash string
var err error
if params.CustomID != "" {
// 检查自定义ID是否已存在
exists, err := database.CheckShortLinkHashExists(params.CustomID)
if err != nil {
respondWithError(c, http.StatusInternalServerError, "数据库错误")
return
}
if exists {
respondWithError(c, http.StatusBadRequest, "自定义ID已存在")
return
}
hash = params.CustomID
} else {
hash, err = generateUniqueHash()
if err != nil {
respondWithError(c, http.StatusInternalServerError, "生成短链接失败")
return
}
}
shortLink := model.ShortLink{
@ -74,11 +91,27 @@ func UpdateLinkHandler(c *gin.Context) {
respondWithError(c, http.StatusBadRequest, "参数错误: "+err.Error())
return
}
// 先获取原有的短链接
existingLink, err := database.FindShortLinkByHash(params.Hash)
if err != nil {
respondWithError(c, http.StatusNotFound, "未找到短链接")
return
}
// 验证密码
if existingLink.Password != params.Password {
respondWithError(c, http.StatusUnauthorized, "密码错误")
return
}
// 更新URL但保持原密码不变
shortLink := model.ShortLink{
Hash: params.Hash,
Url: params.Url,
Password: params.Password,
Password: existingLink.Password, // 保持原密码不变
}
if err := database.SaveShortLink(&shortLink); err != nil {
respondWithError(c, http.StatusInternalServerError, "数据库错误")
return