Compare commits

...

31 Commits

Author SHA1 Message Date
db00433931
Merge pull request #59 from timerzz/main
fix 修复Get函数重试结束后,返回nil,nil的bug
2025-03-24 01:12:06 +11:00
timerzz
5b3a12f00d fix 修复Get函数重试结束后,返回nil,nil的bug 2025-03-23 21:27:05 +08:00
d4d7010d8f
Merge pull request #56 from hausen1012/main
add:生成短链支持自定义id
2025-03-10 12:28:37 +11:00
hz
2331cd4d18 modify: 短链和密码修改为后端生成 2025-03-08 19:02:23 +08:00
hz
88d8653ab5 fix:修复ua标识等两个前端未正常回显问题 2025-03-07 17:41:42 +08:00
hz
cc0b73d7a4 add:生成短链支持自定义id 2025-03-07 17:30:28 +08:00
b57e4cf49f fix ua form 2025-03-05 19:24:48 +11:00
Nite07
cc80e237d6
Merge pull request #48 from 96368a/main
 增加socks5协议支持
2024-11-13 10:31:41 +08:00
96368a
fefb4b895a 增加socks5协议支持 2024-11-13 09:21:31 +08:00
66f214ae10 try to fix ss parser 2024-11-06 18:43:48 +08:00
f7dc78aabc 🐛 2024-10-19 15:39:20 +08:00
6bb2d16e4b 🐛 #46 2024-10-09 11:08:24 +08:00
98ef93c7bb 🐛 #42 2024-10-08 10:05:13 +08:00
6e09c44d17 🐛 #43 2024-10-08 10:01:09 +08:00
42fd251eb5 #42 2024-10-07 16:34:56 +08:00
e504a6cca4 🎨 Refactor package for public import 2024-09-17 13:10:13 +08:00
3cfa4bdf24 ️ Improve 2024-08-11 23:55:47 +08:00
dedbf2bc03 🐛 fix #37 2024-08-04 12:59:55 +08:00
Nite07
7158ad467a
Merge pull request #35 from arusuki/main
🔧  customize HTTP user-agent for fetching subscription from API.
2024-08-04 12:53:06 +08:00
tao-lintian
fd22cd1499 🔧 customize HTTP user-agent for fetching subscription from API. 2024-07-15 21:01:22 +08:00
0946412ea7 🐛 #31 2024-05-21 15:28:09 +08:00
98bca0a7ac 🐛 Cannot parse custom rules 2024-05-21 15:00:19 +08:00
036907fba4 🐛 Parse short link 2024-05-09 12:58:33 +08:00
3e720ec14d 🐛 Fix vless parser lost fingerprint 2024-05-06 02:22:44 +08:00
b73a02bdbf 🐛 Fix vless parser cannot correctly parse some reality/grpc fields 2024-05-05 22:46:01 +08:00
25e47453cb 🔥 Remove test dir, verison length limit 2024-05-04 22:30:46 +08:00
3330412243 🔧 Update docker workflow 2024-04-26 00:04:17 +08:00
35deaa015f 🔥 Deprecate Woodpecker CI in favor of GitHub Actions 2024-04-25 22:23:33 +08:00
ddd297492c ⬆️ Upgrade dependencies 2024-04-24 13:05:10 +08:00
effd22c750 ♻️ Refactor logger
📝 Update README
2024-04-24 13:01:22 +08:00
566965bb6a ♻️ Migrate from gorm/sqlite to boltdb 2024-04-24 12:51:37 +08:00
54 changed files with 1053 additions and 865 deletions

View File

@ -5,4 +5,3 @@ REQUEST_RETRY_TIMES=3
REQUEST_MAX_FILE_SIZE=1048576
CACHE_EXPIRE=300
LOG_LEVEL=info
BASE_PATH=/

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=auto eol=lf

55
.github/workflows/docker.yml vendored Normal file
View File

@ -0,0 +1,55 @@
name: docker
on:
push:
tags:
- "v*"
jobs:
prepare-and-build:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
with:
images: |
nite07/sub2clash
ghcr.io/nitezs/sub2clash
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
type=match,pattern=(alpha|beta|rc),group=1
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
build-args: |
"version=${{ github.ref_name }}"
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
platforms: linux/amd64,linux/arm64,linux/arm/v7

28
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,28 @@
name: release
on:
push:
tags:
- "v*"
permissions:
contents: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v4
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v5
with:
distribution: goreleaser
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

6
.gitignore vendored
View File

@ -2,6 +2,8 @@
dist
subs
logs
sub2clash.db
data
.env
.vscode/settings.json
.vscode/settings.json
test
*test.go

View File

@ -1,24 +1,32 @@
project_name: sub2clash
builds:
- env:
- CGO_ENABLED=0
goos:
- windows
- linux
- darwin
goarch:
- amd64
ldflags:
- -s -w -X sub2clash/constant.Version={{ .Version }}
flags:
- -trimpath
- env:
- CGO_ENABLED=0
goos:
- windows
- linux
- darwin
goarch:
- amd64
- arm64
- arm
- "386"
goarm:
- "6"
- "7"
ldflags:
- -s -w -X sub2clash/constant.Version={{ .Version }}
flags:
- -trimpath
archives:
- format: tar.gz
format_overrides:
- format: zip
goos: windows
wrap_in_directory: true
files:
- LICENSE
- README.md
- templates
- format: tar.gz
format_overrides:
- format: zip
goos: windows
wrap_in_directory: true
files:
- LICENSE
- README.md
- templates
release:
draft: true

4
.vscode/launch.json vendored
View File

@ -5,9 +5,9 @@
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}/main.go",
"program": "${workspaceFolder}",
"output": "${workspaceFolder}/dist/main.exe",
"buildFlags": "-ldflags '-X sub2clash/config.Version=dev'"
"buildFlags": "-ldflags '-X sub2clash/constant.Version=dev'"
}
]
}

View File

@ -1,21 +0,0 @@
when:
- event: tag
ref: refs/tags/v*
steps:
- name: prepare-tags
image: bash
commands:
- |
echo "${CI_COMMIT_TAG##v}" > .tags
if ! echo "${CI_COMMIT_TAG}" | grep -Eq "beta|alpha"; then
echo "latest" > .tags
fi
- name: build
image: woodpeckerci/plugin-docker-buildx
settings:
platforms: linux/amd64
repo: nite07/sub2clash
username: nite07
password:
from_secret: docker_password

View File

@ -1,20 +0,0 @@
when:
- event: tag
ref: refs/tags/v*
steps:
- name: build
image: goreleaser/goreleaser:latest
commands:
- goreleaser release --clean --skip publish
- mkdir release
- mv dist/*.tar.gz release/
- mv dist/*.zip release/
- name: release
image: woodpeckerci/plugin-gitea-release
settings:
files: release/*
api_key:
from_secret: forgejo_token
base-url: https://git.nite07.com
draft: true

View File

@ -5,25 +5,26 @@
## 特性
- 开箱即用的规则、策略组配置
- 自动根据节点名称按国家划分策略组
- 支持多订阅合并
- 支持添加自定义 Rule Provider、Rule
- 支持多种协议
- Shadowsocks
- ShadowsocksR
- Vmess
- Vless Clash.Meta
- Trojan
- Hysteria Clash.Meta
- Hysteria2 Clash.Meta
- 开箱即用的规则、策略组配置
- 自动根据节点名称按国家划分策略组
- 多订阅合并
- 自定义 Rule Provider、Rule
- 支持多种协议
- Shadowsocks
- ShadowsocksR
- Vmess
- Vless Clash.Meta
- Trojan
- Hysteria Clash.Meta
- Hysteria2 Clash.Meta
- Socks5
## 使用
### 运行
### 部署
- [docker compose](./docker-compose.yml)
- 运行[二进制文件](https://github.com/nitezs/sub2clash/releases/latest)
- [docker compose](./docker-compose.yml)
- 运行[二进制文件](https://github.com/nitezs/sub2clash/releases/latest)
### 配置
@ -42,22 +43,18 @@
### API
[API 文档](./API_README.md)
[API 文档](./API.md)
### 模板
可以通过变量自定义模板中的策略组代理节点
解释的不太清楚,可以参考下方默认模板
具体参考下方默认模板
- `<all>` 为添加所有节点
- `<countries>` 为添加所有国家策略组
- `<地区二位字母代码>` 为添加指定地区所有节点,例如 `<hk>` 将添加所有香港节点
- `<all>` 为添加所有节点
- `<countries>` 为添加所有国家策略组
- `<地区二位字母代码>` 为添加指定地区所有节点,例如 `<hk>` 将添加所有香港节点
#### 默认模板
- [Clash](./templates/template_clash.yaml)
- [Clash.Meta](./templates/template_meta.yaml)
## 已知问题
[代理链接解析](./parser)还没有经过严格测试,可能会出现解析错误的情况,如果出现问题请提交 issue
- [Clash](./templates/template_clash.yaml)
- [Clash.Meta](./templates/template_meta.yaml)

View File

@ -2,16 +2,17 @@ package handler
import (
"net/http"
"sub2clash/config"
"sub2clash/model"
"sub2clash/validator"
"github.com/nitezs/sub2clash/config"
"github.com/nitezs/sub2clash/model"
"github.com/nitezs/sub2clash/validator"
"github.com/gin-gonic/gin"
"gopkg.in/yaml.v3"
)
func SubmodHandler(c *gin.Context) {
// 从请求中获取参数
query, err := validator.ParseQuery(c)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
@ -22,7 +23,7 @@ func SubmodHandler(c *gin.Context) {
c.String(http.StatusInternalServerError, err.Error())
return
}
// 输出
if query.NodeListMode {
nodelist := model.NodeList{}
nodelist.Proxies = sub.Proxies

View File

@ -9,11 +9,12 @@ import (
"sort"
"strconv"
"strings"
"sub2clash/common"
"sub2clash/logger"
"sub2clash/model"
"sub2clash/parser"
"sub2clash/validator"
"github.com/nitezs/sub2clash/common"
"github.com/nitezs/sub2clash/logger"
"github.com/nitezs/sub2clash/model"
"github.com/nitezs/sub2clash/parser"
"github.com/nitezs/sub2clash/validator"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
@ -22,17 +23,17 @@ import (
func BuildSub(clashType model.ClashType, query validator.SubValidator, template string) (
*model.Subscription, error,
) {
// 定义变量
var temp = &model.Subscription{}
var sub = &model.Subscription{}
var err error
var templateBytes []byte
// 加载模板
if query.Template != "" {
template = query.Template
}
if strings.HasPrefix(template, "http") {
templateBytes, err = common.LoadSubscription(template, query.Refresh)
templateBytes, err = common.LoadSubscription(template, query.Refresh, query.UserAgent)
if err != nil {
logger.Logger.Debug(
"load template failed", zap.String("template", template), zap.Error(err),
@ -52,16 +53,16 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
return nil, errors.New("加载模板失败: " + err.Error())
}
}
// 解析模板
err = yaml.Unmarshal(templateBytes, &temp)
if err != nil {
logger.Logger.Debug("parse template failed", zap.Error(err))
return nil, errors.New("解析模板失败: " + err.Error())
}
var proxyList []model.Proxy
// 加载订阅
for i := range query.Subs {
data, err := common.LoadSubscription(query.Subs[i], query.Refresh)
data, err := common.LoadSubscription(query.Subs[i], query.Refresh, query.UserAgent)
subName := ""
if strings.Contains(query.Subs[i], "#") {
subName = query.Subs[i][strings.LastIndex(query.Subs[i], "#")+1:]
@ -72,7 +73,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
)
return nil, errors.New("加载订阅失败: " + err.Error())
}
// 解析订阅
err = yaml.Unmarshal(data, &sub)
var newProxies []model.Proxy
if err != nil {
@ -81,7 +82,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
p := common.ParseProxy(strings.Split(string(data), "\n")...)
newProxies = p
} else {
// 如果无法直接解析尝试Base64解码
base64, err := parser.DecodeBase64(string(data))
if err != nil {
logger.Logger.Debug(
@ -104,28 +105,31 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
}
proxyList = append(proxyList, newProxies...)
}
// 添加自定义节点
if len(query.Proxies) != 0 {
proxyList = append(proxyList, common.ParseProxy(query.Proxies...)...)
}
// 给节点添加订阅名称
for i := range proxyList {
if proxyList[i].SubName != "" {
proxyList[i].Name = strings.TrimSpace(proxyList[i].SubName) + " " + strings.TrimSpace(proxyList[i].Name)
}
}
// 去掉配置相同的节点
proxies := make(map[string]*model.Proxy)
newProxies := make([]model.Proxy, 0, len(proxyList))
for i := range proxyList {
key := proxyList[i].Server + strconv.Itoa(proxyList[i].Port) + proxyList[i].Type + proxyList[i].UUID + proxyList[i].Password
if proxyList[i].Network == "ws" {
key += proxyList[i].WSOpts.Path + proxyList[i].WSOpts.Headers["Host"]
}
if _, exist := proxies[key]; !exist {
proxies[key] = &proxyList[i]
newProxies = append(newProxies, proxyList[i])
}
}
proxyList = newProxies
// 删除节点
if strings.TrimSpace(query.Remove) != "" {
newProxyList := make([]model.Proxy, 0, len(proxyList))
for i := range proxyList {
@ -134,17 +138,17 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
logger.Logger.Debug("remove regexp compile failed", zap.Error(err))
return nil, errors.New("remove 参数非法: " + err.Error())
}
// 删除匹配到的节点
if removeReg.MatchString(proxyList[i].Name) {
continue // 如果匹配到要删除的元素,跳过该元素,不添加到新切片中
continue
}
newProxyList = append(newProxyList, proxyList[i]) // 将要保留的元素添加到新切片中
newProxyList = append(newProxyList, proxyList[i])
}
proxyList = newProxyList
}
// 重命名
if len(query.ReplaceKeys) != 0 {
// 创建重命名正则表达式
replaceRegs := make([]*regexp.Regexp, 0, len(query.ReplaceKeys))
for _, v := range query.ReplaceKeys {
replaceReg, err := regexp.Compile(v)
@ -155,7 +159,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
replaceRegs = append(replaceRegs, replaceReg)
}
for i := range proxyList {
// 重命名匹配到的节点
for j, v := range replaceRegs {
if v.MatchString(proxyList[i].Name) {
proxyList[i].Name = v.ReplaceAllString(
@ -165,7 +169,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
}
}
}
// 重名检测
names := make(map[string]int)
for i := range proxyList {
if _, exist := names[proxyList[i].Name]; exist {
@ -175,14 +179,14 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
names[proxyList[i].Name] = 0
}
}
// trim
for i := range proxyList {
proxyList[i].Name = strings.TrimSpace(proxyList[i].Name)
}
// 将新增节点都添加到临时变量 t 中,防止策略组排序错乱
var t = &model.Subscription{}
common.AddProxy(t, query.AutoTest, query.Lazy, clashType, proxyList...)
// 排序策略组
switch query.Sort {
case "sizeasc":
sort.Sort(model.ProxyGroupsSortBySize(t.ProxyGroups))
@ -195,9 +199,9 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
default:
sort.Sort(model.ProxyGroupsSortByName(t.ProxyGroups))
}
// 合并新节点和模板
MergeSubAndTemplate(temp, t, query.IgnoreCountryGrooup)
// 处理自定义规则
for _, v := range query.Rules {
if v.Prepend {
common.PrependRules(temp, v.Rule)
@ -205,7 +209,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
common.AppendRules(temp, v.Rule)
}
}
// 处理自定义 ruleProvider
for _, v := range query.RuleProviders {
hash := sha256.Sum224([]byte(v.Url))
name := hex.EncodeToString(hash[:])
@ -230,8 +234,7 @@ func BuildSub(clashType model.ClashType, query validator.SubValidator, template
}
func MergeSubAndTemplate(temp *model.Subscription, sub *model.Subscription, igcg bool) {
// 只合并节点、策略组
// 统计所有国家策略组名称
var countryGroupNames []string
for _, proxyGroup := range sub.ProxyGroups {
if proxyGroup.IsCountryGrop {
@ -244,9 +247,9 @@ func MergeSubAndTemplate(temp *model.Subscription, sub *model.Subscription, igcg
for _, proxy := range sub.Proxies {
proxyNames = append(proxyNames, proxy.Name)
}
// 将订阅中的节点添加到模板中
temp.Proxies = append(temp.Proxies, sub.Proxies...)
// 将订阅中的策略组添加到模板中
for i := range temp.ProxyGroups {
if temp.ProxyGroups[i].IsCountryGrop {
continue

View File

@ -3,16 +3,17 @@ package handler
import (
_ "embed"
"net/http"
"sub2clash/config"
"sub2clash/model"
"sub2clash/validator"
"github.com/nitezs/sub2clash/config"
"github.com/nitezs/sub2clash/model"
"github.com/nitezs/sub2clash/validator"
"github.com/gin-gonic/gin"
"gopkg.in/yaml.v3"
)
func SubHandler(c *gin.Context) {
// 从请求中获取参数
query, err := validator.ParseQuery(c)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
@ -23,7 +24,7 @@ func SubHandler(c *gin.Context) {
c.String(http.StatusInternalServerError, err.Error())
return
}
// 输出
if query.NodeListMode {
nodelist := model.NodeList{}
nodelist.Proxies = sub.Proxies

View File

@ -1,160 +1,199 @@
package handler
import (
"errors"
"io"
"net/http"
"strconv"
"strings"
"sub2clash/common"
"sub2clash/common/database"
"sub2clash/config"
"sub2clash/logger"
"sub2clash/model"
"sub2clash/validator"
"time"
"github.com/nitezs/sub2clash/common"
"github.com/nitezs/sub2clash/common/database"
"github.com/nitezs/sub2clash/config"
"github.com/nitezs/sub2clash/model"
"github.com/nitezs/sub2clash/validator"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"gorm.io/gorm"
)
func ShortLinkGenHandler(c *gin.Context) {
// 从请求中获取参数
func respondWithError(c *gin.Context, code int, message string) {
c.String(code, message)
c.Abort()
}
func GenerateLinkHandler(c *gin.Context) {
var params validator.ShortLinkGenValidator
if err := c.ShouldBind(&params); err != nil {
c.String(400, "参数错误: "+err.Error())
respondWithError(c, http.StatusBadRequest, "参数错误: "+err.Error())
return
}
if strings.TrimSpace(params.Url) == "" {
c.String(400, "参数错误")
respondWithError(c, http.StatusBadRequest, "URL 不能为空")
return
}
// 生成hash
hash := common.RandomString(config.Default.ShortLinkLength)
var item model.ShortLink
result := database.FindShortLinkByUrl(params.Url, &item)
if result.Error == nil {
if item.Password != params.Password {
item.Password = params.Password
database.SaveShortLink(&item)
c.String(200, item.Hash+"?password="+params.Password)
} else {
c.String(200, item.Hash)
}
return
} else {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
c.String(500, "数据库错误: "+result.Error.Error())
var hash string
var password 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, "短链已存在")
return
}
hash = params.CustomID
password = params.Password
} else {
// 自动生成短链ID和密码
hash, err = generateUniqueHash()
if err != nil {
respondWithError(c, http.StatusInternalServerError, "生成短链接失败")
return
}
if params.Password == "" {
password = common.RandomString(8) // 生成8位随机密码
} else {
password = params.Password
}
}
// 如果记录存在则重新生成hash直到记录不存在
result = database.FindShortLinkByHash(hash, &item)
for result.Error == nil {
hash = common.RandomString(config.Default.ShortLinkLength)
result = database.FindShortLinkByHash(hash, &item)
shortLink := model.ShortLink{
Hash: hash,
Url: params.Url,
Password: password,
}
// 创建记录
database.FirstOrCreateShortLink(
&model.ShortLink{
Hash: hash,
Url: params.Url,
LastRequestTime: -1,
Password: params.Password,
},
)
// 返回短链接
if params.Password != "" {
hash += "?password=" + params.Password
if err := database.SaveShortLink(&shortLink); err != nil {
respondWithError(c, http.StatusInternalServerError, "数据库错误")
return
}
c.String(200, hash)
// 返回生成的短链ID和密码
response := map[string]string{
"hash": hash,
"password": password,
}
c.JSON(http.StatusOK, response)
}
func ShortLinkGetUrlHandler(c *gin.Context) {
var params validator.ShortLinkGetValidator
if err := c.ShouldBindQuery(&params); err != nil {
c.String(400, "参数错误: "+err.Error())
return
func generateUniqueHash() (string, error) {
for {
hash := common.RandomString(config.Default.ShortLinkLength)
exists, err := database.CheckShortLinkHashExists(hash)
if err != nil {
return "", err
}
if !exists {
return hash, nil
}
}
if strings.TrimSpace(params.Hash) == "" {
c.String(400, "参数错误")
return
}
var shortLink model.ShortLink
result := database.FindShortLinkByHash(params.Hash, &shortLink)
if result.Error != nil {
c.String(404, "未找到短链接")
return
}
if shortLink.Password != "" && shortLink.Password != params.Password {
c.String(403, "密码错误")
return
}
c.String(200, shortLink.Url)
}
func ShortLinkGetConfigHandler(c *gin.Context) {
// 获取动态路由
func UpdateLinkHandler(c *gin.Context) {
var params validator.ShortLinkUpdateValidator
if err := c.ShouldBindJSON(&params); err != nil {
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: existingLink.Password, // 保持原密码不变
}
if err := database.SaveShortLink(&shortLink); err != nil {
respondWithError(c, http.StatusInternalServerError, "数据库错误")
return
}
c.String(http.StatusOK, "短链接更新成功")
}
func GetRawConfHandler(c *gin.Context) {
hash := c.Param("hash")
password := c.Query("password")
if strings.TrimSpace(hash) == "" {
c.String(400, "参数错误")
c.String(http.StatusBadRequest, "参数错误")
return
}
// 查询数据库
var shortLink model.ShortLink
result := database.FindShortLinkByHash(hash, &shortLink)
// 重定向
if result.Error != nil {
c.String(404, "未找到短链接或密码错误")
shortLink, err := database.FindShortLinkByHash(hash)
if err != nil {
c.String(http.StatusNotFound, "未找到短链接或密码错误")
return
}
if shortLink.Password != "" && shortLink.Password != password {
c.String(404, "未找到短链接或密码错误")
c.String(http.StatusNotFound, "未找到短链接或密码错误")
return
}
// 更新最后访问时间
shortLink.LastRequestTime = time.Now().Unix()
database.SaveShortLink(&shortLink)
get, err := common.Get("http://localhost:" + strconv.Itoa(config.Default.Port) + "/" + shortLink.Url)
err = database.SaveShortLink(shortLink)
if err != nil {
logger.Logger.Debug("get short link data failed", zap.Error(err))
c.String(500, "请求错误: "+err.Error())
respondWithError(c, http.StatusInternalServerError, "数据库错误")
return
}
all, err := io.ReadAll(get.Body)
response, err := http.Get("http://localhost:" + strconv.Itoa(config.Default.Port) + "/" + shortLink.Url)
if err != nil {
logger.Logger.Debug("read short link data failed", zap.Error(err))
c.String(500, "读取错误: "+err.Error())
respondWithError(c, http.StatusInternalServerError, "请求错误: "+err.Error())
return
}
defer response.Body.Close()
all, err := io.ReadAll(response.Body)
if err != nil {
respondWithError(c, http.StatusInternalServerError, "读取错误: "+err.Error())
return
}
c.String(http.StatusOK, string(all))
}
func ShortLinkUpdateHandler(c *gin.Context) {
var params validator.ShortLinkUpdateValidator
if err := c.ShouldBind(&params); err != nil {
c.String(400, "参数错误: "+err.Error())
}
if strings.TrimSpace(params.Url) == "" {
c.String(400, "参数错误")
func GetRawConfUriHandler(c *gin.Context) {
hash := c.Query("hash")
password := c.Query("password")
if strings.TrimSpace(hash) == "" {
c.String(http.StatusBadRequest, "参数错误")
return
}
var shortLink model.ShortLink
result := database.FindShortLinkByHash(params.Hash, &shortLink)
if result.Error != nil {
c.String(404, "未找到短链接")
shortLink, err := database.FindShortLinkByHash(hash)
if err != nil {
c.String(http.StatusNotFound, "未找到短链接或密码错误")
return
}
if shortLink.Password == "" {
c.String(403, "无法修改无密码短链接")
if shortLink.Password != "" && shortLink.Password != password {
c.String(http.StatusNotFound, "未找到短链接或密码错误")
return
}
if shortLink.Password != params.Password {
c.String(403, "密码错误")
return
}
shortLink.Url = params.Url
database.SaveShortLink(&shortLink)
c.String(200, "更新成功")
c.String(http.StatusOK, shortLink.Url)
}

View File

@ -5,9 +5,10 @@ import (
"html/template"
"log"
"net/http"
"sub2clash/api/handler"
"sub2clash/constant"
"sub2clash/middleware"
"github.com/nitezs/sub2clash/api/handler"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/middleware"
"github.com/gin-gonic/gin"
)
@ -18,7 +19,6 @@ var staticFiles embed.FS
func SetRoute(r *gin.Engine) {
r.Use(middleware.ZapLogger())
// 使用内嵌的模板文件
tpl, err := template.ParseFS(staticFiles, "static/*")
if err != nil {
log.Fatalf("Error parsing templates: %v", err)
@ -33,9 +33,6 @@ func SetRoute(r *gin.Engine) {
r.GET(
"/", func(c *gin.Context) {
version := constant.Version
if len(constant.Version) > 7 {
version = constant.Version[:7]
}
c.HTML(
200, "index.html", gin.H{
"Version": version,
@ -43,33 +40,10 @@ func SetRoute(r *gin.Engine) {
)
},
)
r.GET(
"/clash", func(c *gin.Context) {
handler.SubmodHandler(c)
},
)
r.GET(
"/meta", func(c *gin.Context) {
handler.SubHandler(c)
},
)
r.GET(
"/s/:hash", func(c *gin.Context) {
handler.ShortLinkGetConfigHandler(c)
},
)
r.GET(
"/short", func(c *gin.Context) {
handler.ShortLinkGetUrlHandler(c)
})
r.POST(
"/short", func(c *gin.Context) {
handler.ShortLinkGenHandler(c)
},
)
r.PUT(
"/short", func(c *gin.Context) {
handler.ShortLinkUpdateHandler(c)
},
)
r.GET("/clash", handler.SubmodHandler)
r.GET("/meta", handler.SubHandler)
r.GET("/s/:hash", handler.GetRawConfHandler)
r.POST("/short", handler.GenerateLinkHandler)
r.PUT("/short", handler.UpdateLinkHandler)
r.GET("/short", handler.GetRawConfUriHandler)
}

View File

@ -75,6 +75,12 @@
<label for="proxy">节点分享链接:</label>
<textarea class="form-control" id="proxy" name="proxy" placeholder="每行输入一个节点分享链接" rows="5"></textarea>
</div>
<!-- User Agent -->
<div class="form-group mb-3">
<label for="user-agent">ua标识:</label>
<textarea class="form-control" id="user-agent" name="user-agent"
placeholder="用于获取订阅的http请求中的user-agent标识(可选)" rows="3"></textarea>
</div>
<!-- Refresh -->
<div class="form-check mb-3">
<input class="form-check-input" id="refresh" name="refresh" type="checkbox" />
@ -141,24 +147,27 @@
<div class="form-group mb-5">
<label for="apiLink">配置链接:</label>
<div class="input-group mb-2">
<input class="form-control" id="apiLink" type="text" placeholder="链接" />
<input class="form-control bg-light" id="apiLink" type="text" placeholder="链接" readonly style="cursor: not-allowed;" />
<button class="btn btn-primary" onclick="copyToClipboard('apiLink',this)" type="button">
复制链接
</button>
</div>
<div class="input-group">
<input class="form-control" id="apiShortLink" type="text" placeholder="链接" />
<input class="form-control" id="password" type="text" placeholder="密码" />
<div class="input-group mb-2">
<input class="form-control" id="customId" type="text" placeholder="短链ID可选" />
<input class="form-control" id="password" type="text" placeholder="密码(可选)" />
<button class="btn btn-primary" onclick="generateShortLink()" type="button">
生成短链
</button>
<button class="btn btn-primary" onclick="updateShortLink()" type="button">
更新短链
</button>
<button class="btn btn-primary" onclick="copyToClipboard('apiShortLink',this)" type="button">
复制短链
</button>
</div>
<div class="input-group">
<input class="form-control bg-light" id="apiShortLink" type="text" placeholder="短链接" readonly style="cursor: not-allowed;" />
<button class="btn btn-primary" onclick="updateShortLink()" type="button">
更新短链
</button>
</div>
</div>
<!-- footer-->
@ -172,4 +181,5 @@
</div>
</body>
<script src="./static/index.js"></script>
</html>

View File

@ -1,3 +1,15 @@
function setInputReadOnly(input, readonly) {
if (readonly) {
input.readOnly = true;
input.classList.add('bg-light');
input.style.cursor = 'not-allowed';
} else {
input.readOnly = false;
input.classList.remove('bg-light');
input.style.cursor = 'auto';
}
}
function clearExistingValues() {
// 清除简单输入框和复选框的值
document.getElementById("endpoint").value = "clash";
@ -12,7 +24,23 @@ function clearExistingValues() {
document.getElementById("remove").value = "";
document.getElementById("apiLink").value = "";
document.getElementById("apiShortLink").value = "";
document.getElementById("password").value = "";
// 恢复短链ID和密码输入框状态
const customIdInput = document.getElementById("customId");
const passwordInput = document.getElementById("password");
const generateButton = document.querySelector('button[onclick="generateShortLink()"]');
customIdInput.value = "";
setInputReadOnly(customIdInput, false);
passwordInput.value = "";
setInputReadOnly(passwordInput, false);
// 恢复生成短链按钮状态
generateButton.disabled = false;
generateButton.classList.remove('btn-secondary');
generateButton.classList.add('btn-primary');
document.getElementById("nodeList").checked = false;
// 清除由 createRuleProvider, createReplace, 和 createRule 创建的所有额外输入组
@ -66,6 +94,11 @@ function generateURI() {
// alert("订阅链接和节点分享链接不能同时为空!");
return "";
}
// 获取订阅user-agent标识
const userAgent = document.getElementById("user-agent").value;
queryParams.push(`userAgent=${encodeURIComponent(userAgent)}`);
// 获取复选框的值
const refresh = document.getElementById("refresh").checked;
queryParams.push(`refresh=${refresh ? "true" : "false"}`);
@ -111,17 +144,16 @@ function generateURI() {
queryParams.push(`ruleProvider=${encodeURIComponent(providers.join(","))}`);
let ruleList = [];
for (let i = 0; i < rules.length / 3; i++) {
if (rules[i * 3].value.trim() !== "") {
let rule = rules[i * 3].value;
let prepend = rules[i * 3 + 1].value;
let group = rules[i * 3 + 2].value;
for (let i = 0; i < rules.length / 2; i++) {
if (rules[i * 2].value.trim() !== "") {
let rule = rules[i * 2].value;
let prepend = rules[i * 2 + 1].value;
// 是否存在空值
if (rule.trim() === "" || prepend.trim() === "" || group.trim() === "") {
if (rule.trim() === "" || prepend.trim() === "") {
// alert("Rule 中存在空值,请检查后重试!");
return "";
}
ruleList.push(`[${rule},${prepend},${group}]`);
ruleList.push(`[${rule},${prepend}]`);
}
}
queryParams.push(`rule=${encodeURIComponent(ruleList.join(","))}`);
@ -175,13 +207,41 @@ async function parseInputURL() {
let hash = url.pathname.substring(url.pathname.lastIndexOf("/s/") + 3);
let q = new URLSearchParams();
let password = url.searchParams.get("password");
if (password === null) {
alert("仅可解析加密短链");
return;
}
q.append("hash", hash);
q.append("password", password);
try {
const response = await axios.get("./short?" + q.toString());
url = new URL(window.location.href + response.data);
document.querySelector("#apiShortLink").value = inputURL;
document.querySelector("#password").value = password;
// 回显配置链接
const apiLinkInput = document.querySelector("#apiLink");
apiLinkInput.value = `${window.location.origin}${window.location.pathname}${response.data}`;
setInputReadOnly(apiLinkInput, true);
// 回显短链相关信息
const apiShortLinkInput = document.querySelector("#apiShortLink");
apiShortLinkInput.value = inputURL;
setInputReadOnly(apiShortLinkInput, true);
// 设置短链ID和密码并设置为只读
const customIdInput = document.querySelector("#customId");
const passwordInput = document.querySelector("#password");
const generateButton = document.querySelector('button[onclick="generateShortLink()"]');
customIdInput.value = hash;
setInputReadOnly(customIdInput, true);
passwordInput.value = password;
setInputReadOnly(passwordInput, true);
// 禁用生成短链按钮
generateButton.disabled = true;
generateButton.classList.add('btn-secondary');
generateButton.classList.remove('btn-primary');
} catch (error) {
console.log(error);
alert("获取短链失败,请检查密码!");
@ -247,6 +307,17 @@ async function parseInputURL() {
);
}
if (params.has("userAgent")) {
document.getElementById("user-agent").value = decodeURIComponent(
params.get("userAgent")
);
}
if (params.has("ignoreCountryGroup")) {
document.getElementById("igcg").checked =
params.get("ignoreCountryGroup") === "true";
}
if (params.has("replace")) {
parseAndFillReplaceParams(decodeURIComponent(params.get("replace")));
}
@ -310,13 +381,12 @@ function parseAndFillRuleProviderParams(ruleProviderParams) {
function parseAndFillRuleParams(ruleParams) {
const ruleGroup = document.getElementById("ruleGroup");
let matches;
const regex = /\[(.*?),(.*?),(.*?)\]/g;
const regex = /\[(.*?),(.*?)\]/g;
const str = decodeURIComponent(ruleParams);
while ((matches = regex.exec(str)) !== null) {
const div = createRule();
div.children[0].value = matches[1];
div.children[1].value = matches[2];
div.children[2].value = matches[3];
ruleGroup.appendChild(div);
}
}
@ -366,7 +436,6 @@ function createRule() {
div.innerHTML = `
<input type="text" class="form-control" name="rule" placeholder="Rule">
<input type="text" class="form-control" name="rule" placeholder="Prepend">
<input type="text" class="form-control" name="rule" placeholder="Group">
<button type="button" class="btn btn-danger" onclick="removeElement(this)">删除</button>
`;
return div;
@ -422,21 +491,25 @@ function generateURL() {
return;
}
apiLink.value = `${window.location.origin}${window.location.pathname}${uri}`;
setInputReadOnly(apiLink, true);
}
function generateShortLink() {
const apiShortLink = document.getElementById("apiShortLink");
const password = document.getElementById("password");
const customId = document.getElementById("customId");
let uri = generateURI();
if (uri === "") {
return;
}
axios
.post(
"./short",
{
url: uri,
password: password.value.trim(),
customId: customId.value.trim()
},
{
headers: {
@ -445,11 +518,20 @@ function generateShortLink() {
}
)
.then((response) => {
apiShortLink.value = `${window.location.origin}${window.location.pathname}s/${response.data}`;
// 设置返回的短链ID和密码
customId.value = response.data.hash;
password.value = response.data.password;
// 生成完整的短链接
const shortLink = `${window.location.origin}${window.location.pathname}s/${response.data.hash}?password=${response.data.password}`;
apiShortLink.value = shortLink;
})
.catch((error) => {
console.log(error);
alert("生成短链失败,请重试!");
if (error.response && error.response.data) {
alert(error.response.data);
} else {
alert("生成短链失败,请重试!");
}
});
}
@ -462,7 +544,7 @@ function updateShortLink() {
hash = u.pathname.substring(u.pathname.lastIndexOf("/s/") + 3);
}
if (password.value.trim() === "") {
alert("请输入密码!");
alert("请输入密码进行验证");
return;
}
let uri = generateURI();
@ -484,11 +566,17 @@ function updateShortLink() {
}
)
.then((response) => {
alert("更新短链成功!");
alert(`短链 ${hash} 更新成功!`);
})
.catch((error) => {
console.log(error);
alert(error.response.data);
if (error.response && error.response.status === 401) {
alert("密码错误,请输入正确的原密码!");
} else if (error.response && error.response.data) {
alert(error.response.data);
} else {
alert("更新短链失败,请重试!");
}
});
}

View File

@ -1,56 +1,69 @@
package database
import (
"encoding/json"
"errors"
"path/filepath"
"sub2clash/common"
"sub2clash/logger"
"sub2clash/model"
"github.com/glebarez/sqlite"
"go.uber.org/zap"
"gorm.io/gorm"
"github.com/nitezs/sub2clash/model"
"go.etcd.io/bbolt"
)
var DB *gorm.DB
var DB *bbolt.DB
func ConnectDB() error {
// 用上面的数据库连接初始化 gorm
err := common.MKDir("data")
if err != nil {
return err
}
db, err := gorm.Open(
sqlite.Open(filepath.Join("data", "sub2clash.db")), &gorm.Config{
Logger: nil,
},
)
path := filepath.Join("data", "sub2clash.db")
db, err := bbolt.Open(path, 0600, nil)
if err != nil {
return err
}
DB = db
err = db.AutoMigrate(&model.ShortLink{})
if err != nil {
return db.Update(func(tx *bbolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("ShortLinks"))
return err
})
}
func FindShortLinkByHash(hash string) (*model.ShortLink, error) {
var shortLink model.ShortLink
err := DB.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte("ShortLinks"))
v := b.Get([]byte(hash))
if v == nil {
return errors.New("ShortLink not found")
}
return json.Unmarshal(v, &shortLink)
})
if err != nil {
return nil, err
}
return nil
return &shortLink, nil
}
func FindShortLinkByUrl(url string, shortLink *model.ShortLink) *gorm.DB {
logger.Logger.Debug("find short link by url", zap.String("url", url))
return DB.Where("url = ?", url).First(&shortLink)
func SaveShortLink(shortLink *model.ShortLink) error {
return DB.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte("ShortLinks"))
encoded, err := json.Marshal(shortLink)
if err != nil {
return err
}
return b.Put([]byte(shortLink.Hash), encoded)
})
}
func FindShortLinkByHash(hash string, shortLink *model.ShortLink) *gorm.DB {
logger.Logger.Debug("find short link by hash", zap.String("hash", hash))
return DB.Where("hash = ?", hash).First(&shortLink)
}
func SaveShortLink(shortLink *model.ShortLink) {
logger.Logger.Debug("save short link", zap.String("hash", shortLink.Hash))
DB.Save(shortLink)
}
func FirstOrCreateShortLink(shortLink *model.ShortLink) {
logger.Logger.Debug("first or create short link", zap.String("hash", shortLink.Hash))
DB.FirstOrCreate(shortLink)
func CheckShortLinkHashExists(hash string) (bool, error) {
exists := false
err := DB.View(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte("ShortLinks"))
v := b.Get([]byte(hash))
exists = v != nil
return nil
})
if err != nil {
return false, err
}
return exists, nil
}

View File

@ -2,31 +2,53 @@ package common
import (
"errors"
"fmt"
"net/http"
"sub2clash/config"
"time"
"github.com/nitezs/sub2clash/config"
)
func Get(url string) (resp *http.Response, err error) {
type GetConfig struct {
userAgent string
}
type GetOption func(*GetConfig)
func WithUserAgent(userAgent string) GetOption {
return func(config *GetConfig) {
config.userAgent = userAgent
}
}
func Get(url string, options ...GetOption) (resp *http.Response, err error) {
retryTimes := config.Default.RequestRetryTimes
haveTried := 0
retryDelay := time.Second // 延迟1秒再重试
retryDelay := time.Second
getConfig := GetConfig{}
for _, option := range options {
option(&getConfig)
}
var req *http.Request
var get *http.Response
for haveTried < retryTimes {
client := &http.Client{}
//client.Timeout = time.Second * 10
req, err := http.NewRequest("GET", url, nil)
req, err = http.NewRequest("GET", url, nil)
if err != nil {
haveTried++
time.Sleep(retryDelay)
continue
}
get, err := client.Do(req)
if getConfig.userAgent != "" {
req.Header.Set("User-Agent", getConfig.userAgent)
}
get, err = client.Do(req)
if err != nil {
haveTried++
time.Sleep(retryDelay)
continue
} else {
// 如果文件大小大于设定,直接返回错误
if get != nil && get.ContentLength > config.Default.RequestMaxFileSize {
return nil, errors.New("文件过大")
}
@ -34,5 +56,5 @@ func Get(url string) (resp *http.Response, err error) {
}
}
return nil, err
return nil, fmt.Errorf("请求失败:%v", err)
}

View File

@ -26,5 +26,8 @@ func MkEssentialDir() error {
if err := MKDir("logs"); err != nil {
return errors.New("create logs dir failed" + err.Error())
}
if err := MKDir("data"); err != nil {
return errors.New("create data dir failed" + err.Error())
}
return nil
}

View File

@ -2,16 +2,17 @@ package common
import (
"strings"
"sub2clash/constant"
"sub2clash/logger"
"sub2clash/model"
"sub2clash/parser"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/logger"
"github.com/nitezs/sub2clash/model"
"github.com/nitezs/sub2clash/parser"
"go.uber.org/zap"
)
func GetContryName(countryKey string) string {
// 创建一个切片包含所有的国家映射
countryMaps := []map[string]string{
model.CountryFlag,
model.CountryChineseName,
@ -19,11 +20,9 @@ func GetContryName(countryKey string) string {
model.CountryEnglishName,
}
// 对每一个映射进行检查
for i, countryMap := range countryMaps {
if i == 2 {
// 对ISO匹配做特殊处理
// 根据常用分割字符分割字符串
splitChars := []string{"-", "_", " "}
key := make([]string, 0)
for _, splitChar := range splitChars {
@ -34,9 +33,9 @@ func GetContryName(countryKey string) string {
}
}
}
// 对每一个分割后的字符串进行检查
for _, v := range key {
// 如果匹配到了国家
if country, ok := countryMap[strings.ToUpper(v)]; ok {
return country
}
@ -56,7 +55,7 @@ func AddProxy(
lazy bool, clashType model.ClashType, proxies ...model.Proxy,
) {
proxyTypes := model.GetSupportProxyTypes(clashType)
// 添加节点
for _, proxy := range proxies {
if !proxyTypes[proxy.Type] {
continue
@ -106,7 +105,7 @@ func ParseProxy(proxies ...string) []model.Proxy {
if proxy != "" {
var proxyItem model.Proxy
var err error
// 解析节点
if strings.HasPrefix(proxy, constant.ShadowsocksPrefix) {
proxyItem, err = parser.ParseShadowsocks(proxy)
}
@ -128,6 +127,9 @@ func ParseProxy(proxies ...string) []model.Proxy {
if strings.HasPrefix(proxy, constant.HysteriaPrefix) {
proxyItem, err = parser.ParseHysteria(proxy)
}
if strings.HasPrefix(proxy, constant.SocksPrefix) {
proxyItem, err = parser.ParseSocks(proxy)
}
if err == nil {
result = append(result, proxyItem)
} else {

View File

@ -3,7 +3,7 @@ package common
import "math/rand"
func RandomString(length int) string {
// 生成随机字符串
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var result []byte
for i := 0; i < length; i++ {

View File

@ -3,7 +3,8 @@ package common
import (
"fmt"
"strings"
"sub2clash/model"
"github.com/nitezs/sub2clash/model"
)
func PrependRuleProvider(

View File

@ -5,19 +5,21 @@ import (
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sub2clash/config"
"sync"
"time"
"github.com/nitezs/sub2clash/config"
)
var subsDir = "subs"
var fileLock sync.RWMutex
func LoadSubscription(url string, refresh bool) ([]byte, error) {
func LoadSubscription(url string, refresh bool, userAgent string) ([]byte, error) {
if refresh {
return FetchSubscriptionFromAPI(url)
return FetchSubscriptionFromAPI(url, userAgent)
}
hash := sha256.Sum224([]byte(url))
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
@ -26,9 +28,9 @@ func LoadSubscription(url string, refresh bool) ([]byte, error) {
if !os.IsNotExist(err) {
return nil, err
}
return FetchSubscriptionFromAPI(url)
return FetchSubscriptionFromAPI(url, userAgent)
}
lastGetTime := stat.ModTime().Unix() // 单位是秒
lastGetTime := stat.ModTime().Unix()
if lastGetTime+config.Default.CacheExpire > time.Now().Unix() {
file, err := os.Open(fileName)
if err != nil {
@ -47,21 +49,21 @@ func LoadSubscription(url string, refresh bool) ([]byte, error) {
}
return subContent, nil
}
return FetchSubscriptionFromAPI(url)
return FetchSubscriptionFromAPI(url, userAgent)
}
func FetchSubscriptionFromAPI(url string) ([]byte, error) {
func FetchSubscriptionFromAPI(url string, userAgent string) ([]byte, error) {
hash := sha256.Sum224([]byte(url))
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:]))
resp, err := Get(url)
resp, err := Get(url, WithUserAgent(userAgent))
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
if Body != nil {
_ = Body.Close()
defer func(resp *http.Response) {
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
}(resp.Body)
}(resp)
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)

View File

@ -7,8 +7,6 @@ import (
"path/filepath"
)
// LoadTemplate 加载模板
// templates 模板文件名
func LoadTemplate(template string) ([]byte, error) {
tPath := filepath.Join("templates", template)
if _, err := os.Stat(tPath); err == nil {

View File

@ -3,7 +3,8 @@ package common
import (
"os"
"path/filepath"
"sub2clash/config"
"github.com/nitezs/sub2clash/config"
)
func writeTemplate(path string, template string) error {

View File

@ -9,4 +9,5 @@ const (
TrojanPrefix string = "trojan://"
VLESSPrefix string = "vless://"
VMessPrefix string = "vmess://"
SocksPrefix string = "socks"
)

33
go.mod
View File

@ -1,53 +1,42 @@
module sub2clash
module github.com/nitezs/sub2clash
go 1.21
require (
github.com/gin-gonic/gin v1.9.1
github.com/glebarez/sqlite v1.10.0
github.com/joho/godotenv v1.5.1
go.etcd.io/bbolt v1.3.9
go.uber.org/zap v1.27.0
golang.org/x/text v0.14.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v3 v3.0.1
gorm.io/gorm v1.25.7
)
require (
github.com/bytedance/sonic v1.11.3 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
github.com/chenzhuoyu/iasm v0.9.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/bytedance/sonic v1.11.5 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.3 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/glebarez/go-sqlite v1.22.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.19.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/natefinch/lumberjack v2.0.0+incompatible // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/pelletier/go-toml/v2 v2.1.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/pelletier/go-toml/v2 v2.2.1 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/arch v0.7.0 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/net v0.22.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.19.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
modernc.org/libc v1.44.0 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.7.2 // indirect
modernc.org/sqlite v1.29.4 // indirect
)

96
go.sum
View File

@ -1,29 +1,21 @@
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
github.com/bytedance/sonic v1.11.3 h1:jRN+yEjakWh8aK5FzrciUHG8OFXK+4/KrAX/ysEtHAA=
github.com/bytedance/sonic v1.11.3/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA=
github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0=
github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
github.com/bytedance/sonic v1.11.5 h1:G00FYjjqll5iQ1PYXynbg/hyzqBqavH8Mo9/oTopd9k=
github.com/bytedance/sonic v1.11.5/go.mod h1:X2PC2giUdj/Cv2lliWFLk6c/DUQok5rViJSemeB0wDw=
github.com/bytedance/sonic/loader v0.1.0/go.mod h1:UmRT+IRTGKz/DAkzcEGzyVqQFJ7H9BqwBO3pm9H/+HY=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.3 h1:b5J/l8xolB7dyDTTmhJP2oTs5LdrjyrUFuNxdfq5hAg=
github.com/cloudwego/base64x v0.1.3/go.mod h1:1+1K5BUHIQzyapgpF7LwvOGAEDicKtt1umPV+aN8pi8=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=
github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
github.com/glebarez/sqlite v1.10.0 h1:u4gt8y7OND/cCei/NMHmfbLxF6xP2wgKcT/BJf2pYkc=
github.com/glebarez/sqlite v1.10.0/go.mod h1:IJ+lfSOmiekhQsFTJRx/lHtGYmCdtAiTaf5wI9u5uHA=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
@ -37,14 +29,6 @@ github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MG
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
@ -62,30 +46,28 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM=
github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI=
github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pelletier/go-toml/v2 v2.2.1 h1:9TA9+T8+8CUCO2+WYnDLCgrYi9+omqKXyjDtosvtEhg=
github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
go.etcd.io/bbolt v1.3.9 h1:8x7aARPEXiXbHmtUwAIv7eV2fQFHrLLavdiJ3uzJXoI=
go.etcd.io/bbolt v1.3.9/go.mod h1:zaO32+Ti0PK1ivdPtgMESzuzL2VPoIG1PCQNvOdo/dE=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
@ -95,52 +77,26 @@ go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
modernc.org/cc/v4 v4.19.3 h1:vE9kmJqUcyvNOf8F2Hn8od14SOMq34BiqcZ2tMzLk5c=
modernc.org/cc/v4 v4.19.3/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
modernc.org/ccgo/v4 v4.10.1 h1:qi+3luLv0LR5UkLmZyKXZxIC4K/136vcAUoYYeGSS+g=
modernc.org/ccgo/v4 v4.10.1/go.mod h1:9YDnb1IIvHymh899K5a++jza0JIWygZPTc5dlh7xvhQ=
modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
modernc.org/libc v1.44.0 h1:71bbnKgb0mCg7GOOI/PHlzz7Bv6obELGNKnIEeowX8c=
modernc.org/libc v1.44.0/go.mod h1:RRqfGVjvILF5AdNP3RPCiihj7+Dn2pIBrdlU60lA9vs=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=
modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
modernc.org/sqlite v1.29.4 h1:mbvQTJ3Tl5Vz+wLA6z8hdBFSeNQ0XXQ+KVwn8NkUliw=
modernc.org/sqlite v1.29.4/go.mod h1:MjUIBKZ+tU/lqjNLbVAAMjsQPdWdA/ciwdhsT9kBwk8=
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

View File

@ -1,70 +1,52 @@
package logger
import (
"path/filepath"
"sync"
"time"
"os"
"strings"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gopkg.in/natefinch/lumberjack.v2"
)
var (
Logger *zap.Logger
lock sync.Mutex
logLevel string
)
var Logger *zap.Logger
func InitLogger(level string) {
logLevel = level
buildLogger()
go rotateLogs()
func InitLogger(logLevel string) {
logger := zap.New(buildZapCore(getZapLogLevel(logLevel)))
Logger = logger
}
func buildLogger() {
lock.Lock()
defer lock.Unlock()
var level zapcore.Level
switch logLevel {
case "error":
level = zap.ErrorLevel
func buildZapCore(logLevel zapcore.Level) zapcore.Core {
fileWriter := zapcore.AddSync(&lumberjack.Logger{
Filename: "logs/app.log",
MaxSize: 500,
MaxBackups: 3,
MaxAge: 28,
Compress: true,
})
consoleWriter := zapcore.AddSync(os.Stdout)
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
fileCore := zapcore.NewCore(zapcore.NewJSONEncoder(encoderConfig), fileWriter, logLevel)
consoleCore := zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), consoleWriter, logLevel)
combinedCore := zapcore.NewTee(fileCore, consoleCore)
return combinedCore
}
func getZapLogLevel(logLevel string) zapcore.Level {
switch strings.ToLower(logLevel) {
case "debug":
level = zap.DebugLevel
return zap.DebugLevel
case "warn":
level = zap.WarnLevel
return zap.WarnLevel
case "error":
return zap.ErrorLevel
case "info":
level = zap.InfoLevel
return zap.InfoLevel
default:
level = zap.InfoLevel
}
zapConfig := zap.NewProductionConfig()
zapConfig.Encoding = "console"
zapConfig.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
zapConfig.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
zapConfig.OutputPaths = []string{"stdout", getLogFileName("info")}
zapConfig.ErrorOutputPaths = []string{"stderr", getLogFileName("error")}
zapConfig.Level = zap.NewAtomicLevelAt(level)
var err error
Logger, err = zapConfig.Build()
if err != nil {
panic("log failed" + err.Error())
}
}
// 根据日期获得日志文件
func getLogFileName(name string) string {
return filepath.Join("logs", time.Now().Format("2006-01-02")+"-"+name+".log")
}
func rotateLogs() {
for {
now := time.Now()
nextMidnight := time.Date(
now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location(),
).Add(24 * time.Hour)
durationUntilMidnight := nextMidnight.Sub(now)
time.Sleep(durationUntilMidnight)
buildLogger()
return zap.InfoLevel
}
}

29
main.go
View File

@ -4,11 +4,12 @@ import (
_ "embed"
"io"
"strconv"
"sub2clash/api"
"sub2clash/common"
"sub2clash/common/database"
"sub2clash/config"
"sub2clash/logger"
"github.com/nitezs/sub2clash/api"
"github.com/nitezs/sub2clash/common"
"github.com/nitezs/sub2clash/common/database"
"github.com/nitezs/sub2clash/config"
"github.com/nitezs/sub2clash/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@ -22,24 +23,24 @@ var templateClash string
func init() {
var err error
// 创建文件夹
err = common.MkEssentialDir()
if err != nil {
logger.Logger.Panic("create essential dir failed", zap.Error(err))
}
// 加载配置
err = config.LoadConfig()
// 初始化日志
logger.InitLogger(config.Default.LogLevel)
if err != nil {
logger.Logger.Panic("load config failed", zap.Error(err))
}
// 写入默认模板
err = common.WriteDefalutTemplate(templateMeta, templateClash)
if err != nil {
logger.Logger.Panic("write default template failed", zap.Error(err))
}
// 连接数据库
err = database.ConnectDB()
if err != nil {
logger.Logger.Panic("database connect failed", zap.Error(err))
@ -48,13 +49,13 @@ func init() {
}
func main() {
// 设置运行模式
gin.SetMode(gin.ReleaseMode)
// 关闭 Gin 的日志输出
gin.DefaultWriter = io.Discard
// 创建路由
r := gin.Default()
// 设置路由
api.SetRoute(r)
logger.Logger.Info("server is running at http://localhost:" + strconv.Itoa(config.Default.Port))
err := r.Run(":" + strconv.Itoa(config.Default.Port))

View File

@ -2,9 +2,10 @@ package middleware
import (
"strconv"
"sub2clash/logger"
"time"
"github.com/nitezs/sub2clash/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)

View File

@ -14,6 +14,7 @@ func GetSupportProxyTypes(clashType ClashType) map[string]bool {
"ssr": true,
"vmess": true,
"trojan": true,
"socks5": true,
}
}
if clashType == ClashMeta {
@ -25,6 +26,7 @@ func GetSupportProxyTypes(clashType ClashType) map[string]bool {
"vless": true,
"hysteria": true,
"hysteria2": true,
"socks5": true,
}
}
return nil

View File

@ -1,8 +1,5 @@
package model
// https://zh.wikipedia.org/wiki/%E5%8C%BA%E5%9F%9F%E6%8C%87%E7%A4%BA%E7%AC%A6
// https://zh.wikipedia.org/zh-sg/ISO_3166-1%E4%BA%8C%E4%BD%8D%E5%AD%97%E6%AF%8D%E4%BB%A3%E7%A0%81
var CountryEnglishName = map[string]string{
"Andorra": "安道尔(AD)",
"United Arab Emirates": "阿联酋(AE)",

View File

@ -5,62 +5,83 @@ type SmuxStruct struct {
}
type Proxy struct {
Name string `yaml:"name,omitempty"`
Server string `yaml:"server,omitempty"`
Port int `yaml:"port,omitempty"`
Type string `yaml:"type,omitempty"`
Cipher string `yaml:"cipher,omitempty"`
Password string `yaml:"password,omitempty"`
UDP bool `yaml:"udp,omitempty"`
UUID string `yaml:"uuid,omitempty"`
Network string `yaml:"network,omitempty"`
Flow string `yaml:"flow,omitempty"`
TLS bool `yaml:"tls,omitempty"`
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
Plugin string `yaml:"plugin,omitempty"`
PluginOpts map[string]any `yaml:"plugin-opts,omitempty"`
Smux SmuxStruct `yaml:"smux,omitempty"`
Sni string `yaml:"sni,omitempty"`
AllowInsecure bool `yaml:"allow-insecure,omitempty"`
Fingerprint string `yaml:"fingerprint,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
Alpn []string `yaml:"alpn,omitempty"`
XUDP bool `yaml:"xudp,omitempty"`
Servername string `yaml:"servername,omitempty"`
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
AlterID int `yaml:"alterId,omitempty"`
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
RealityOpts RealityOptions `yaml:"reality-opts,omitempty"`
Protocol string `yaml:"protocol,omitempty"`
Obfs string `yaml:"obfs,omitempty"`
ObfsParam string `yaml:"obfs-param,omitempty"`
ProtocolParam string `yaml:"protocol-param,omitempty"`
Remarks []string `yaml:"remarks,omitempty"`
HTTPOpts HTTPOptions `yaml:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `yaml:"h2-opts,omitempty"`
PacketAddr bool `yaml:"packet-addr,omitempty"`
PacketEncoding string `yaml:"packet-encoding,omitempty"`
GlobalPadding bool `yaml:"global-padding,omitempty"`
AuthenticatedLength bool `yaml:"authenticated-length,omitempty"`
UDPOverTCP bool `yaml:"udp-over-tcp,omitempty"`
UDPOverTCPVersion int `yaml:"udp-over-tcp-version,omitempty"`
SubName string `yaml:"-"`
Up string `yaml:"up,omitempty"`
Down string `yaml:"down,omitempty"`
CustomCA string `yaml:"ca,omitempty"`
CustomCAString string `yaml:"ca-str,omitempty"`
CWND int `yaml:"cwnd,omitempty"`
Auth string `yaml:"auth,omitempty"`
ReceiveWindowConn int `yaml:"recv-window-conn,omitempty"`
ReceiveWindow int `yaml:"recv-window,omitempty"`
DisableMTUDiscovery bool `yaml:"disable-mtu-discovery,omitempty"`
FastOpen bool `yaml:"fast-open,omitempty"`
HopInterval int `yaml:"hop-interval,omitempty"`
Ports string `yaml:"ports,omitempty"`
AuthStringOLD string `yaml:"auth_str,omitempty"`
AuthString string `yaml:"auth-str,omitempty"`
Name string `yaml:"name,omitempty"`
Server string `yaml:"server,omitempty"`
Port int `yaml:"port,omitempty"`
Type string `yaml:"type,omitempty"`
Cipher string `yaml:"cipher,omitempty"`
Username string `yaml:"username,omitempty"`
Password string `yaml:"password,omitempty"`
UDP bool `yaml:"udp,omitempty"`
UUID string `yaml:"uuid,omitempty"`
Network string `yaml:"network,omitempty"`
Flow string `yaml:"flow,omitempty"`
TLS bool `yaml:"tls,omitempty"`
ClientFingerprint string `yaml:"client-fingerprint,omitempty"`
Plugin string `yaml:"plugin,omitempty"`
PluginOpts map[string]any `yaml:"plugin-opts,omitempty"`
Smux SmuxStruct `yaml:"smux,omitempty"`
Sni string `yaml:"sni,omitempty"`
AllowInsecure bool `yaml:"allow-insecure,omitempty"`
Fingerprint string `yaml:"fingerprint,omitempty"`
SkipCertVerify bool `yaml:"skip-cert-verify,omitempty"`
Alpn []string `yaml:"alpn,omitempty"`
XUDP bool `yaml:"xudp,omitempty"`
Servername string `yaml:"servername,omitempty"`
WSOpts WSOptions `yaml:"ws-opts,omitempty"`
AlterID int `yaml:"alterId,omitempty"`
GrpcOpts GrpcOptions `yaml:"grpc-opts,omitempty"`
RealityOpts RealityOptions `yaml:"reality-opts,omitempty"`
Protocol string `yaml:"protocol,omitempty"`
Obfs string `yaml:"obfs,omitempty"`
ObfsParam string `yaml:"obfs-param,omitempty"`
ProtocolParam string `yaml:"protocol-param,omitempty"`
Remarks []string `yaml:"remarks,omitempty"`
HTTPOpts HTTPOptions `yaml:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `yaml:"h2-opts,omitempty"`
PacketAddr bool `yaml:"packet-addr,omitempty"`
PacketEncoding string `yaml:"packet-encoding,omitempty"`
GlobalPadding bool `yaml:"global-padding,omitempty"`
AuthenticatedLength bool `yaml:"authenticated-length,omitempty"`
UDPOverTCP bool `yaml:"udp-over-tcp,omitempty"`
UDPOverTCPVersion int `yaml:"udp-over-tcp-version,omitempty"`
SubName string `yaml:"-"`
Up string `yaml:"up,omitempty"`
Down string `yaml:"down,omitempty"`
CustomCA string `yaml:"ca,omitempty"`
CustomCAString string `yaml:"ca-str,omitempty"`
CWND int `yaml:"cwnd,omitempty"`
Auth string `yaml:"auth,omitempty"`
ReceiveWindowConn int `yaml:"recv-window-conn,omitempty"`
ReceiveWindow int `yaml:"recv-window,omitempty"`
DisableMTUDiscovery bool `yaml:"disable-mtu-discovery,omitempty"`
FastOpen bool `yaml:"fast-open,omitempty"`
HopInterval int `yaml:"hop-interval,omitempty"`
Ports string `yaml:"ports,omitempty"`
AuthStringOLD string `yaml:"auth_str,omitempty"`
AuthString string `yaml:"auth-str,omitempty"`
Ip string `yaml:"ip,omitempty"`
Ipv6 string `yaml:"ipv6,omitempty"`
PrivateKey string `yaml:"private-key,omitempty"`
Workers int `yaml:"workers,omitempty"`
MTU int `yaml:"mtu,omitempty"`
PersistentKeepalive int `yaml:"persistent-keepalive,omitempty"`
Peers []WireGuardPeerOption `yaml:"peers,omitempty"`
RemoteDnsResolve bool `yaml:"remote-dns-resolve,omitempty"`
Dns []string `yaml:"dns,omitempty"`
}
type WireGuardPeerOption struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
PublicKey string `yaml:"public-key,omitempty"`
PreSharedKey string `yaml:"pre-shared-key,omitempty"`
Reserved []uint8 `yaml:"reserved,omitempty"`
AllowedIPs []string `yaml:"allowed-ips,omitempty"`
}
type _Proxy Proxy
func (p Proxy) MarshalYAML() (interface{}, error) {
switch p.Type {
case "vmess":
@ -77,6 +98,7 @@ func (p Proxy) MarshalYAML() (interface{}, error) {
return ProxyToHysteria(p), nil
case "hysteria2":
return ProxyToHysteria2(p), nil
default:
return _Proxy(p), nil
}
return nil, nil
}

View File

@ -9,12 +9,12 @@ type ProxyGroup struct {
Type string `yaml:"type,omitempty"`
Name string `yaml:"name,omitempty"`
Proxies []string `yaml:"proxies,omitempty"`
IsCountryGrop bool `yaml:"-"` // 是否是国家分组
IsCountryGrop bool `yaml:"-"`
Url string `yaml:"url,omitempty"`
Interval int `yaml:"interval,omitempty"`
Tolerance int `yaml:"tolerance,omitempty"`
Lazy bool `yaml:"lazy"`
Size int `yaml:"-"` // 代理数量
Size int `yaml:"-"`
DisableUDP bool `yaml:"disable-udp,omitempty"`
Strategy string `yaml:"strategy,omitempty"`
Icon string `yaml:"icon,omitempty"`
@ -42,16 +42,15 @@ func (p ProxyGroupsSortBySize) Len() int {
}
func (p ProxyGroupsSortByName) Less(i, j int) bool {
// 定义一组备选语言:首选英语,其次中文
tags := []language.Tag{
language.English,
language.Chinese,
}
matcher := language.NewMatcher(tags)
// 假设我们的请求语言是 "zh"(中文),则使用匹配器找到最佳匹配的语言
bestMatch, _, _ := matcher.Match(language.Make("zh"))
// 使用最佳匹配的语言进行排序
c := collate.New(bestMatch)
return c.CompareString(p[i].Name, p[j].Name) < 0
}

View File

@ -7,11 +7,11 @@ type Hysteria struct {
Port int `yaml:"port,omitempty"`
Ports string `yaml:"ports,omitempty"`
Protocol string `yaml:"protocol,omitempty"`
ObfsProtocol string `yaml:"obfs-protocol,omitempty"` // compatible with Stash
ObfsProtocol string `yaml:"obfs-protocol,omitempty"`
Up string `yaml:"up"`
UpSpeed int `yaml:"up-speed,omitempty"` // compatible with Stash
UpSpeed int `yaml:"up-speed,omitempty"`
Down string `yaml:"down"`
DownSpeed int `yaml:"down-speed,omitempty"` // compatible with Stash
DownSpeed int `yaml:"down-speed,omitempty"`
Auth string `yaml:"auth,omitempty"`
AuthStringOLD string `yaml:"auth_str,omitempty"`
AuthString string `yaml:"auth-str,omitempty"`

View File

@ -1,7 +1,7 @@
package model
type ShortLink struct {
Hash string `gorm:"primary_key"`
Hash string
Url string
Password string
LastRequestTime int64

View File

@ -103,7 +103,6 @@ type IPTables struct {
DnsRedirect bool `yaml:"dns-redirect,omitempty" json:"dns-redirect"`
}
// EBpf config
type EBpf struct {
RedirectToTun []string `yaml:"redirect-to-tun,omitempty" json:"redirect-to-tun"`
AutoRedir []string `yaml:"auto-redir,omitempty" json:"auto-redir"`

View File

@ -7,7 +7,7 @@ import (
func DecodeBase64(s string) (string, error) {
s = strings.TrimSpace(s)
// url safe
if strings.Contains(s, "-") || strings.Contains(s, "_") {
s = strings.Replace(s, "-", "+", -1)
s = strings.Replace(s, "_", "/", -1)

View File

@ -1,11 +1,13 @@
package parser
import (
"fmt"
"net/url"
"strconv"
"strings"
"sub2clash/constant"
"sub2clash/model"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/model"
)
func ParseHysteria(proxy string) (model.Proxy, error) {
@ -13,25 +15,31 @@ func ParseHysteria(proxy string) (model.Proxy, error) {
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
}
proxy = strings.TrimPrefix(proxy, constant.HysteriaPrefix)
urlParts := strings.SplitN(proxy, "?", 2)
if len(urlParts) != 2 {
link, err := url.Parse(proxy)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing character '?' in url",
Message: "url parse error",
Raw: proxy,
}
}
server := link.Hostname()
if server == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host",
Raw: proxy,
}
}
serverInfo := strings.SplitN(urlParts[0], ":", 2)
if len(serverInfo) != 2 {
portStr := link.Port()
if portStr == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host or port",
Message: "missing server port",
Raw: proxy,
}
}
server, portStr := serverInfo[0], serverInfo[1]
port, err := ParsePort(portStr)
if err != nil {
@ -42,16 +50,9 @@ func ParseHysteria(proxy string) (model.Proxy, error) {
}
}
params, err := url.ParseQuery(urlParts[1])
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrCannotParseParams,
Raw: proxy,
Message: err.Error(),
}
}
query := link.Query()
protocol, auth, insecure, upmbps, downmbps, obfs, alpnStr := params.Get("protocol"), params.Get("auth"), params.Get("insecure"), params.Get("upmbps"), params.Get("downmbps"), params.Get("obfs"), params.Get("alpn")
protocol, auth, insecure, upmbps, downmbps, obfs, alpnStr := query.Get("protocol"), query.Get("auth"), query.Get("insecure"), query.Get("upmbps"), query.Get("downmbps"), query.Get("obfs"), query.Get("alpn")
insecureBool, err := strconv.ParseBool(insecure)
if err != nil {
insecureBool = false
@ -63,10 +64,11 @@ func ParseHysteria(proxy string) (model.Proxy, error) {
alpn = strings.Split(alpnStr, ",")
}
remarks := server + ":" + portStr
if params.Get("remarks") != "" {
remarks = params.Get("remarks")
remarks := link.Fragment
if remarks == "" {
remarks = fmt.Sprintf("%s:%s", server, portStr)
}
remarks = strings.TrimSpace(remarks)
result := model.Proxy{
Type: "hysteria",
@ -77,7 +79,7 @@ func ParseHysteria(proxy string) (model.Proxy, error) {
Down: downmbps,
Auth: auth,
Obfs: obfs,
SkipCertVerify: insecure == "1",
SkipCertVerify: insecureBool,
Alpn: alpn,
Protocol: protocol,
AllowInsecure: insecureBool,

View File

@ -1,10 +1,12 @@
package parser
import (
"fmt"
"net/url"
"strings"
"sub2clash/constant"
"sub2clash/model"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/model"
)
func ParseHysteria2(proxy string) (model.Proxy, error) {
@ -13,64 +15,53 @@ func ParseHysteria2(proxy string) (model.Proxy, error) {
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
}
proxy = strings.TrimPrefix(proxy, constant.Hysteria2Prefix1)
proxy = strings.TrimPrefix(proxy, constant.Hysteria2Prefix2)
urlParts := strings.SplitN(proxy, "@", 2)
if len(urlParts) != 2 {
link, err := url.Parse(proxy)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing character '@' in url",
Raw: proxy,
}
}
password := urlParts[0]
serverInfo := strings.SplitN(urlParts[1], "/?", 2)
if len(serverInfo) != 2 {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing params in url",
Raw: proxy,
}
}
paramStr := serverInfo[1]
serverAndPort := strings.SplitN(serverInfo[0], ":", 2)
var server string
var portStr string
if len(serverAndPort) == 1 {
portStr = "443"
} else if len(serverAndPort) == 2 {
server, portStr = serverAndPort[0], serverAndPort[1]
} else {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host or port",
Message: "url parse error",
Raw: proxy,
}
}
username := link.User.Username()
password, exist := link.User.Password()
if !exist {
password = username
}
query := link.Query()
server := link.Hostname()
if server == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host",
Raw: proxy,
}
}
portStr := link.Port()
if portStr == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server port",
Raw: proxy,
}
}
port, err := ParsePort(portStr)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidPort,
Message: err.Error(),
Raw: proxy,
Type: ErrInvalidPort,
Raw: portStr,
}
}
params, err := url.ParseQuery(paramStr)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrCannotParseParams,
Raw: proxy,
Message: err.Error(),
}
}
remarks, network, obfs, obfsPassword, pinSHA256, insecure, sni := params.Get("name"), params.Get("network"), params.Get("obfs"), params.Get("obfs-password"), params.Get("pinSHA256"), params.Get("insecure"), params.Get("sni")
enableTLS := pinSHA256 != ""
network, obfs, obfsPassword, pinSHA256, insecure, sni := query.Get("network"), query.Get("obfs"), query.Get("obfs-password"), query.Get("pinSHA256"), query.Get("insecure"), query.Get("sni")
enableTLS := pinSHA256 != "" || sni != ""
insecureBool := insecure == "1"
remarks := link.Fragment
if remarks == "" {
remarks = fmt.Sprintf("%s:%s", server, portStr)
}
remarks = strings.TrimSpace(remarks)
result := model.Proxy{
Type: "hysteria2",

View File

@ -1,83 +1,98 @@
package parser
import (
"fmt"
"net/url"
"strings"
"sub2clash/constant"
"sub2clash/model"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/model"
)
func ParseShadowsocks(proxy string) (model.Proxy, error) {
if !strings.HasPrefix(proxy, constant.ShadowsocksPrefix) {
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
}
proxy = strings.TrimPrefix(proxy, constant.ShadowsocksPrefix)
urlParts := strings.SplitN(proxy, "@", 2)
if len(urlParts) != 2 {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing character '@' in url",
Raw: proxy,
}
}
var serverAndPort []string
if !strings.Contains(urlParts[0], ":") {
decoded, err := DecodeBase64(urlParts[0])
if !strings.Contains(proxy, "@") {
s := strings.SplitN(proxy, "#", 2)
d, err := DecodeBase64(strings.TrimPrefix(s[0], "ss://"))
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "invalid base64 encoded",
Message: "url parse error",
Raw: proxy,
}
}
urlParts[0] = decoded
if len(s) == 2 {
proxy = "ss://" + d + "#" + s[1]
} else {
proxy = "ss://" + d
}
}
credentials := strings.SplitN(urlParts[0], ":", 2)
if len(credentials) != 2 {
link, err := url.Parse(proxy)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host or port",
Message: "url parse error",
Raw: proxy,
}
}
method, password := credentials[0], credentials[1]
serverInfo := strings.SplitN(urlParts[1], "#", 2)
serverAndPort = strings.SplitN(serverInfo[0], ":", 2)
server, portStr := serverAndPort[0], serverAndPort[1]
if len(serverInfo) != 2 {
server := link.Hostname()
if server == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host or port",
Message: "missing server host",
Raw: proxy,
}
}
portStr := link.Port()
if portStr == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server port",
Raw: proxy,
}
}
port, err := ParsePort(portStr)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidPort,
Message: err.Error(),
Raw: proxy,
Type: ErrInvalidStruct,
Raw: proxy,
}
}
var remarks string
if len(serverInfo) == 2 {
unescape, err := url.QueryUnescape(serverInfo[1])
method := link.User.Username()
password, _ := link.User.Password()
if password == "" {
user, err := DecodeBase64(method)
if err == nil {
methodAndPass := strings.SplitN(user, ":", 2)
if len(methodAndPass) == 2 {
method = methodAndPass[0]
password = methodAndPass[1]
}
}
}
if isLikelyBase64(password) {
password, err = DecodeBase64(password)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "cannot unescape remarks",
Message: "password decode error",
Raw: proxy,
}
}
remarks = strings.TrimSpace(unescape)
} else {
remarks = strings.TrimSpace(server + ":" + portStr)
}
remarks := link.Fragment
if remarks == "" {
remarks = fmt.Sprintf("%s:%s", server, portStr)
}
remarks = strings.TrimSpace(remarks)
result := model.Proxy{
Type: "ss",
Cipher: method,
@ -89,3 +104,17 @@ func ParseShadowsocks(proxy string) (model.Proxy, error) {
return result, nil
}
func isLikelyBase64(s string) bool {
if len(s)%4 == 0 && strings.HasSuffix(s, "=") && !strings.Contains(strings.TrimSuffix(s, "="), "=") {
s = strings.TrimSuffix(s, "=")
chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
for _, c := range s {
if !strings.ContainsRune(chars, c) {
return false
}
}
return true
}
return false
}

View File

@ -4,8 +4,9 @@ import (
"net/url"
"strconv"
"strings"
"sub2clash/constant"
"sub2clash/model"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/model"
)
func ParseShadowsocksR(proxy string) (model.Proxy, error) {
@ -27,7 +28,14 @@ func ParseShadowsocksR(proxy string) (model.Proxy, error) {
protocol := parts[2]
method := parts[3]
obfs := parts[4]
password := parts[5]
password, err := DecodeBase64(parts[5])
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Raw: proxy,
Message: err.Error(),
}
}
port, err := ParsePort(parts[1])
if err != nil {
return model.Proxy{}, &ParseError{

79
parser/socks.go Normal file
View File

@ -0,0 +1,79 @@
package parser
import (
"fmt"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/model"
"net/url"
"strings"
)
func ParseSocks(proxy string) (model.Proxy, error) {
if !strings.HasPrefix(proxy, constant.SocksPrefix) {
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
}
link, err := url.Parse(proxy)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "url parse error",
Raw: proxy,
}
}
server := link.Hostname()
if server == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host",
Raw: proxy,
}
}
portStr := link.Port()
if portStr == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server port",
Raw: proxy,
}
}
port, err := ParsePort(portStr)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidPort,
Raw: portStr,
}
}
remarks := link.Fragment
if remarks == "" {
remarks = fmt.Sprintf("%s:%s", server, portStr)
}
remarks = strings.TrimSpace(remarks)
encodeStr := link.User.Username()
var username, password string
if encodeStr != "" {
decodeStr, err := DecodeBase64(encodeStr)
splitStr := strings.Split(decodeStr, ":")
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "url parse error",
Raw: proxy,
}
}
username = splitStr[0]
if len(splitStr) == 2 {
password = splitStr[1]
}
}
return model.Proxy{
Type: "socks5",
Name: remarks,
Server: server,
Port: port,
Username: username,
Password: password,
}, nil
}

View File

@ -1,55 +1,43 @@
package parser
import (
"fmt"
"net/url"
"strings"
"sub2clash/constant"
"sub2clash/model"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/model"
)
// ParseTrojan 解析给定的Trojan代理URL并返回Proxy结构。
func ParseTrojan(proxy string) (model.Proxy, error) {
if !strings.HasPrefix(proxy, constant.TrojanPrefix) {
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
}
proxy = strings.TrimPrefix(proxy, constant.TrojanPrefix)
urlParts := strings.SplitN(proxy, "@", 2)
if len(urlParts) != 2 {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing character '@' in url",
Raw: proxy,
}
}
password := strings.TrimSpace(urlParts[0])
serverInfo := strings.SplitN(urlParts[1], "#", 2)
serverAndPortAndParams := strings.SplitN(serverInfo[0], "?", 2)
if len(serverAndPortAndParams) != 2 {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing character '?' in url",
Raw: proxy,
}
}
serverAndPort := strings.SplitN(serverAndPortAndParams[0], ":", 2)
if len(serverAndPort) != 2 {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host or port",
Raw: proxy,
}
}
server, portStr := serverAndPort[0], serverAndPort[1]
params, err := url.ParseQuery(serverAndPortAndParams[1])
link, err := url.Parse(proxy)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrCannotParseParams,
Type: ErrInvalidStruct,
Message: "url parse error",
Raw: proxy,
}
}
password := link.User.Username()
server := link.Hostname()
if server == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host",
Raw: proxy,
}
}
portStr := link.Port()
if portStr == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server port",
Raw: proxy,
Message: err.Error(),
}
}
@ -62,14 +50,14 @@ func ParseTrojan(proxy string) (model.Proxy, error) {
}
}
remarks := ""
if len(serverInfo) == 2 {
remarks, _ = url.QueryUnescape(strings.TrimSpace(serverInfo[1]))
} else {
remarks = serverAndPort[0]
remarks := link.Fragment
if remarks == "" {
remarks = fmt.Sprintf("%s:%s", server, portStr)
}
remarks = strings.TrimSpace(remarks)
network, security, alpnStr, sni, pbk, sid, fp, path, host, serviceName := params.Get("type"), params.Get("security"), params.Get("alpn"), params.Get("sni"), params.Get("pbk"), params.Get("sid"), params.Get("fp"), params.Get("path"), params.Get("host"), params.Get("serviceName")
query := link.Query()
network, security, alpnStr, sni, pbk, sid, fp, path, host, serviceName := query.Get("type"), query.Get("security"), query.Get("alpn"), query.Get("sni"), query.Get("pbk"), query.Get("sid"), query.Get("fp"), query.Get("path"), query.Get("host"), query.Get("serviceName")
var alpn []string
if strings.Contains(alpnStr, ",") {
@ -78,9 +66,6 @@ func ParseTrojan(proxy string) (model.Proxy, error) {
alpn = nil
}
// enableUTLS := fp != ""
// 构建Proxy结构体
result := model.Proxy{
Type: "trojan",
Server: server,
@ -116,14 +101,6 @@ func ParseTrojan(proxy string) (model.Proxy, error) {
}
}
// if network == "http" {
// // 未查到相关支持文档
// }
// if network == "quic" {
// // 未查到相关支持文档
// }
if network == "grpc" {
result.GrpcOpts = model.GrpcOptions{
GrpcServiceName: serviceName,

View File

@ -1,10 +1,12 @@
package parser
import (
"fmt"
"net/url"
"strings"
"sub2clash/constant"
"sub2clash/model"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/model"
)
func ParseVless(proxy string) (model.Proxy, error) {
@ -12,34 +14,24 @@ func ParseVless(proxy string) (model.Proxy, error) {
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
}
urlParts := strings.SplitN(strings.TrimPrefix(proxy, constant.VLESSPrefix), "@", 2)
if len(urlParts) != 2 {
link, err := url.Parse(proxy)
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing character '@' in url",
Message: "url parse error",
Raw: proxy,
}
}
serverInfo := strings.SplitN(urlParts[1], "#", 2)
serverAndPortAndParams := strings.SplitN(serverInfo[0], "?", 2)
if len(serverAndPortAndParams) != 2 {
server := link.Hostname()
if server == "" {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing character '?' in url",
Message: "missing server host",
Raw: proxy,
}
}
serverAndPort := strings.SplitN(serverAndPortAndParams[0], ":", 2)
if len(serverAndPort) != 2 {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host or port",
Raw: proxy,
}
}
server, portStr := serverAndPort[0], serverAndPort[1]
portStr := link.Port()
port, err := ParsePort(portStr)
if err != nil {
return model.Proxy{}, &ParseError{
@ -49,40 +41,10 @@ func ParseVless(proxy string) (model.Proxy, error) {
}
}
params, err := url.ParseQuery(serverAndPortAndParams[1])
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrCannotParseParams,
Raw: proxy,
Message: err.Error(),
}
}
query := link.Query()
uuid := link.User.Username()
flow, security, alpnStr, sni, insecure, fp, pbk, sid, path, host, serviceName, _type := query.Get("flow"), query.Get("security"), query.Get("alpn"), query.Get("sni"), query.Get("allowInsecure"), query.Get("fp"), query.Get("pbk"), query.Get("sid"), query.Get("path"), query.Get("host"), query.Get("serviceName"), query.Get("type")
remarks := ""
if len(serverInfo) == 2 {
if strings.Contains(serverInfo[1], "|") {
remarks = strings.SplitN(serverInfo[1], "|", 2)[1]
} else {
remarks, err = url.QueryUnescape(serverInfo[1])
if err != nil {
return model.Proxy{}, &ParseError{
Type: ErrCannotParseParams,
Raw: proxy,
Message: err.Error(),
}
}
}
} else {
remarks, err = url.QueryUnescape(server)
if err != nil {
return model.Proxy{}, err
}
}
uuid := strings.TrimSpace(urlParts[0])
flow, security, alpnStr, sni, insecure, fp, pbk, sid, path, host, serviceName, _type := params.Get("flow"), params.Get("security"), params.Get("alpn"), params.Get("sni"), params.Get("allowInsecure"), params.Get("fp"), params.Get("pbk"), params.Get("sid"), params.Get("path"), params.Get("host"), params.Get("serviceName"), params.Get("type")
// enableUTLS := fp != ""
insecureBool := insecure == "1"
var alpn []string
if strings.Contains(alpnStr, ",") {
@ -90,6 +52,11 @@ func ParseVless(proxy string) (model.Proxy, error) {
} else {
alpn = nil
}
remarks := link.Fragment
if remarks == "" {
remarks = fmt.Sprintf("%s:%s", server, portStr)
}
remarks = strings.TrimSpace(remarks)
result := model.Proxy{
Type: "vless",
@ -105,15 +72,17 @@ func ParseVless(proxy string) (model.Proxy, error) {
result.Alpn = alpn
result.Sni = sni
result.AllowInsecure = insecureBool
result.Fingerprint = fp
result.ClientFingerprint = fp
}
if security == "reality" {
result.TLS = true
result.Servername = sni
result.RealityOpts = model.RealityOptions{
PublicKey: pbk,
ShortID: sid,
}
result.ClientFingerprint = fp
}
if _type == "ws" {
@ -127,16 +96,19 @@ func ParseVless(proxy string) (model.Proxy, error) {
}
}
// if _type == "quic" {
// // 未查到相关支持文档
// }
if _type == "grpc" {
result.Network = "grpc"
result.Servername = serviceName
result.GrpcOpts = model.GrpcOptions{
GrpcServiceName: serviceName,
}
}
if _type == "http" {
result.HTTPOpts = model.HTTPOptions{}
result.HTTPOpts.Headers = map[string][]string{}
result.HTTPOpts.Path = strings.Split(path, ",")
hosts, err := url.QueryUnescape(host)
if err != nil {
return model.Proxy{}, &ParseError{
@ -146,10 +118,9 @@ func ParseVless(proxy string) (model.Proxy, error) {
}
}
result.Network = "http"
result.HTTPOpts = model.HTTPOptions{
Headers: map[string][]string{"Host": strings.Split(hosts, ",")},
if hosts != "" {
result.HTTPOpts.Headers["host"] = strings.Split(host, ",")
}
}
return result, nil

View File

@ -5,8 +5,9 @@ import (
"net/url"
"strconv"
"strings"
"sub2clash/constant"
"sub2clash/model"
"github.com/nitezs/sub2clash/constant"
"github.com/nitezs/sub2clash/model"
)
func ParseVmess(proxy string) (model.Proxy, error) {
@ -100,10 +101,6 @@ func ParseVmess(proxy string) (model.Proxy, error) {
}
}
// if vmess.Net == "quic" {
// // 未查到相关支持文档
// }
if vmess.Net == "grpc" {
result.GrpcOpts = model.GrpcOptions{
GrpcServiceName: vmess.Path,

View File

@ -1,5 +1,4 @@
port: 7890
socks-port: 7891
mixed-port: 7890
allow-lan: true
mode: Rule
log-level: info

View File

@ -1,5 +1,4 @@
port: 7890
socks-port: 7891
mixed-port: 7890
allow-lan: true
mode: Rule
log-level: info

View File

@ -1,22 +0,0 @@
package test
import (
"strings"
"testing"
)
func TestParser(t *testing.T) {
// res, err := parser.ParseTrojan("trojan://Abse64hhjewrs@test.com:8443?type=ws&path=%2Fx&host=test.com&security=tls&fp=&alpn=http%2F1.1&sni=test.com#test")
// if err != nil {
// t.Log(err.Error())
// t.Fail()
// }
// bytes, err := yaml.Marshal(res)
// if err != nil {
// t.Log(err.Error())
// t.Fail()
// }
// t.Log(string(bytes))
t.Log(strings.SplitN("123456", "/?", 2))
}

View File

@ -3,10 +3,11 @@ package validator
type ShortLinkGenValidator struct {
Url string `form:"url" binding:"required"`
Password string `form:"password"`
CustomID string `form:"customId"`
}
type ShortLinkGetValidator struct {
Hash string `form:"hash" binding:"required"` // Hash: 短链接
type GetUrlValidator struct {
Hash string `form:"hash" binding:"required"`
Password string `form:"password"`
}

View File

@ -31,6 +31,7 @@ type SubValidator struct {
ReplaceTo []string `form:"-" binding:""`
NodeListMode bool `form:"nodeList,default=false" binding:""`
IgnoreCountryGrooup bool `form:"ignoreCountryGroup,default=false" binding:""`
UserAgent string `form:"userAgent" binding:""`
}
type RuleProviderStruct struct {
@ -110,7 +111,7 @@ func ParseQuery(c *gin.Context) (SubValidator, error) {
},
)
}
// 校验 Rule-Provider 是否有重名
names := make(map[string]bool)
for _, ruleProvider := range query.RuleProviders {
if _, ok := names[ruleProvider.Name]; ok {