feat: 增加短链生成

This commit is contained in:
2023-09-17 15:52:37 +08:00
parent 38dbea4a2a
commit 6b08b2cb86
14 changed files with 206 additions and 34 deletions

View File

@ -1,7 +1,7 @@
package controller
import (
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"errors"
"gopkg.in/yaml.v3"
@ -14,7 +14,7 @@ import (
"sub2clash/validator"
)
func BuildSub(clashType model.ClashType, query validator.SubQuery, template string) (
func BuildSub(clashType model.ClashType, query validator.SubValidator, template string) (
*model.Subscription, error,
) {
// 定义变量
@ -85,7 +85,7 @@ func BuildSub(clashType model.ClashType, query validator.SubQuery, template stri
}
// 处理自定义 ruleProvider
for _, v := range query.RuleProviders {
hash := md5.Sum([]byte(v.Url))
hash := sha256.Sum224([]byte(v.Url))
name := hex.EncodeToString(hash[:])
provider := model.RuleProvider{
Type: "http",

View File

@ -0,0 +1,50 @@
package controller
import (
"crypto/sha256"
"encoding/hex"
"github.com/gin-gonic/gin"
"sub2clash/model"
"sub2clash/utils/database"
"sub2clash/validator"
"time"
)
func ShortLinkGenHandler(c *gin.Context) {
// 从请求中获取参数
var params validator.ShortLinkGenValidator
if err := c.ShouldBind(&params); err != nil {
c.String(400, "参数错误: "+err.Error())
}
// 生成短链接
//hash := utils.RandomString(6)
shortLink := sha256.Sum224([]byte(params.Url))
hash := hex.EncodeToString(shortLink[:])
// 存入数据库
database.DB.FirstOrCreate(
&model.ShortLink{
Hash: hash,
Url: params.Url,
LastRequestTime: -1,
},
)
// 返回短链接
c.String(200, hash)
}
func ShortLinkGetHandler(c *gin.Context) {
// 获取动态路由
hash := c.Param("hash")
// 查询数据库
var shortLink model.ShortLink
result := database.DB.Where("hash = ?", hash).First(&shortLink)
// 更新最后访问时间
shortLink.LastRequestTime = time.Now().Unix()
database.DB.Save(&shortLink)
// 重定向
if result.Error != nil {
c.String(404, "未找到短链接")
return
}
c.Redirect(302, "/"+shortLink.Url)
}