diff --git a/.gitignore b/.gitignore
index 3711d7e..4081dca 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,4 +3,4 @@ dist
subs
test
logs
-dist/
+sub2clash.db
\ No newline at end of file
diff --git a/api/controller/default.go b/api/controller/default.go
index 1225494..c45f72d 100644
--- a/api/controller/default.go
+++ b/api/controller/default.go
@@ -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",
diff --git a/api/controller/short_link.go b/api/controller/short_link.go
new file mode 100644
index 0000000..ae5035d
--- /dev/null
+++ b/api/controller/short_link.go
@@ -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(¶ms); 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)
+}
diff --git a/api/route.go b/api/route.go
index e56cc39..51dc3aa 100644
--- a/api/route.go
+++ b/api/route.go
@@ -30,4 +30,14 @@ func SetRoute(r *gin.Engine) {
controller.SubHandler(c)
},
)
+ r.POST(
+ "/short", func(c *gin.Context) {
+ controller.ShortLinkGenHandler(c)
+ },
+ )
+ r.GET(
+ "/s/:hash", func(c *gin.Context) {
+ controller.ShortLinkGetHandler(c)
+ },
+ )
}
diff --git a/api/templates/index.html b/api/templates/index.html
index 2e75aa0..9cb3a4b 100644
--- a/api/templates/index.html
+++ b/api/templates/index.html
@@ -15,6 +15,9 @@
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous">
+
+
+