1
0
mirror of https://github.com/nitezs/sub2clash.git synced 2024-12-23 14:34:41 -05:00
This commit is contained in:
Nite07 2023-09-12 18:40:24 +08:00
commit d894fea89e
25 changed files with 2179 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.idea
dist
subs
templates

37
README.md Normal file
View File

@ -0,0 +1,37 @@
# sub2clash
将订阅链接转换为 Clash、Clash.Meta 配置
## 特性
- 开箱即用的规则、策略组配置
- 自动根据节点名称按国家划分策略组
- 支持协议
- [x] Shadowsocks
- [x] ShadowsocksR
- [x] Vmess
- [x] Vless
- [x] Trojan
- [ ] Hysteria
- [ ] TUIC
- [ ] WireGuard
## API
### /clash
获取 Clash 配置链接
| Query 参数 | 类型 | 说明 |
| ---------- | ------ | --------------------------------- |
| sub | string | 订阅链接 |
| refresh | bool | 强制获取新配置(默认缓存 5 分钟) |
### /meta
获取 Meta 配置链接
| Query 参数 | 类型 | 说明 |
| ---------- | ------ | --------------------------------- |
| sub | string | 订阅链接 |
| refresh | bool | 强制获取新配置(默认缓存 5 分钟) |

35
api/controller/clash.go Normal file
View File

@ -0,0 +1,35 @@
package controller
import (
"net/http"
"net/url"
"sub/config"
"sub/validator"
"github.com/gin-gonic/gin"
"gopkg.in/yaml.v3"
)
func SubmodHandler(c *gin.Context) {
// 从请求中获取参数
var query validator.SubQuery
if err := c.ShouldBind(&query); err != nil {
c.String(http.StatusBadRequest, "参数错误: "+err.Error())
return
}
query.Sub, _ = url.QueryUnescape(query.Sub)
// 混合订阅和模板节点
sub, err := MixinSubTemp(query, config.Default.ClashTemplate)
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
// 添加自定义节点、规则
// 输出
bytes, err := yaml.Marshal(sub)
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
c.String(http.StatusOK, string(bytes))
}

51
api/controller/default.go Normal file
View File

@ -0,0 +1,51 @@
package controller
import (
"errors"
"gopkg.in/yaml.v3"
"strings"
"sub/model"
"sub/parser"
"sub/utils"
"sub/validator"
)
func MixinSubTemp(query validator.SubQuery, template string) (*model.Subscription, error) {
// 定义变量
var temp *model.Subscription
var sub *model.Subscription
// 加载模板
template, err := utils.LoadTemplate(template)
if err != nil {
return nil, errors.New("加载模板失败: " + err.Error())
}
// 解析模板
err = yaml.Unmarshal([]byte(template), &temp)
if err != nil {
return nil, errors.New("解析模板失败: " + err.Error())
}
// 加载订阅
data, err := utils.LoadSubscription(
query.Sub,
query.Refresh,
)
if err != nil {
return nil, errors.New("加载订阅失败: " + err.Error())
}
// 解析订阅
var proxyList []model.Proxy
err = yaml.Unmarshal(data, &sub)
if err != nil {
// 如果无法直接解析尝试Base64解码
base64, err := parser.DecodeBase64(string(data))
if err != nil {
return nil, errors.New("加载订阅失败: " + err.Error())
}
proxyList = utils.ParseProxy(strings.Split(base64, "\n")...)
} else {
proxyList = sub.Proxies
}
// 添加节点
utils.AddProxy(temp, proxyList...)
return temp, nil
}

36
api/controller/meta.go Normal file
View File

@ -0,0 +1,36 @@
package controller
import (
_ "embed"
"net/http"
"net/url"
"sub/config"
"sub/validator"
"github.com/gin-gonic/gin"
"gopkg.in/yaml.v3"
)
func SubHandler(c *gin.Context) {
// 从请求中获取参数
var query validator.SubQuery
if err := c.ShouldBind(&query); err != nil {
c.String(http.StatusBadRequest, "参数错误: "+err.Error())
return
}
query.Sub, _ = url.QueryUnescape(query.Sub)
// 混合订阅和模板节点
sub, err := MixinSubTemp(query, config.Default.MetaTemplate)
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
// 添加自定义节点、规则
// 输出
marshal, err := yaml.Marshal(sub)
if err != nil {
c.String(http.StatusInternalServerError, "YAML序列化失败: "+err.Error())
return
}
c.String(http.StatusOK, string(marshal))
}

19
api/route.go Normal file
View File

@ -0,0 +1,19 @@
package api
import (
"github.com/gin-gonic/gin"
"sub/api/controller"
)
func SetRoute(r *gin.Engine) {
r.GET(
"/clash", func(c *gin.Context) {
controller.SubmodHandler(c)
},
)
r.GET(
"/meta", func(c *gin.Context) {
controller.SubHandler(c)
},
)
}

16
config/config.go Normal file
View File

@ -0,0 +1,16 @@
package config
type Config struct {
Port int //TODO: 使用自定义端口
MetaTemplate string
ClashTemplate string
}
var Default *Config
func init() {
Default = &Config{
MetaTemplate: "template-meta.yaml",
ClashTemplate: "template-clash.yaml",
}
}

32
go.mod Normal file
View File

@ -0,0 +1,32 @@
module sub
go 1.21
require (
github.com/bytedance/sonic v1.10.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
github.com/chenzhuoyu/iasm v0.9.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.9.1 // 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.15.3 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.5.0 // indirect
golang.org/x/crypto v0.13.0 // indirect
golang.org/x/net v0.15.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/text v0.13.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

84
go.sum Normal file
View File

@ -0,0 +1,84 @@
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.10.0 h1:qtNZduETEIWJVIyDl01BeNxur2rW9OwTQ/yBqFRkKEk=
github.com/bytedance/sonic v1.10.0/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 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo=
github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
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/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.15.3 h1:S+sSpunYjNPDuXkWbK+x+bA7iXiW296KG4dL3X7xUZo=
github.com/go-playground/validator/v10 v10.15.3/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=
github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
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/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
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/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.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
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.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y=
golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
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.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
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=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

83
main.go Normal file
View File

@ -0,0 +1,83 @@
package main
import (
_ "embed"
"fmt"
"github.com/gin-gonic/gin"
"os"
"path/filepath"
"sub/api"
"sub/config"
)
//go:embed templates/template-meta.yaml
var templateMeta string
//go:embed templates/template-clash.yaml
var templateClash string
func writeTemplate(path string, template string) error {
tPath := filepath.Join(
"templates", path,
)
if _, err := os.Stat(tPath); os.IsNotExist(err) {
file, err := os.Create(tPath)
if err != nil {
fmt.Println(err)
return err
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Println(err)
}
}(file)
_, err = file.WriteString(template)
if err != nil {
fmt.Println(err)
return err
}
}
return nil
}
func mkDir(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
fmt.Println(err)
return err
}
}
return nil
}
func init() {
if err := mkDir("subs"); err != nil {
os.Exit(1)
}
if err := mkDir("templates"); err != nil {
os.Exit(1)
}
if err := writeTemplate(config.Default.MetaTemplate, templateMeta); err != nil {
os.Exit(1)
}
if err := writeTemplate(config.Default.ClashTemplate, templateClash); err != nil {
os.Exit(1)
}
}
func main() {
// 设置运行模式
gin.SetMode(gin.ReleaseMode)
// 创建路由
r := gin.Default()
// 设置路由
api.SetRoute(r)
fmt.Println("Server is running at 8011")
err := r.Run(":8011")
if err != nil {
fmt.Println(err)
return
}
}

1034
model/contryCode.go Normal file

File diff suppressed because it is too large Load Diff

83
model/proxy.go Normal file
View File

@ -0,0 +1,83 @@
package model
type PluginOptsStruct struct {
Mode string `yaml:"mode"`
}
type SmuxStruct struct {
Enabled bool `yaml:"enable"`
}
type HeaderStruct struct {
Host string `yaml:"Host"`
}
type WSOptsStruct struct {
Path string `yaml:"path,omitempty"`
Headers HeaderStruct `yaml:"headers,omitempty"`
MaxEarlyData int `yaml:"max-early-data,omitempty"`
EarlyDataHeaderName string `yaml:"early-data-header-name,omitempty"`
}
type Vmess struct {
V string `json:"v"`
Ps string `json:"ps"`
Add string `json:"add"`
Port string `json:"port"`
Id string `json:"id"`
Aid string `json:"aid"`
Scy string `json:"scy"`
Net string `json:"net"`
Type string `json:"type"`
Host string `json:"host"`
Path string `json:"path"`
Tls string `json:"tls"`
Sni string `json:"sni"`
Alpn string `json:"alpn"`
Fp string `json:"fp"`
}
type GRPCOptsStruct struct {
GRPCServiceName string `yaml:"grpc-service-name,omitempty"`
}
type RealityOptsStruct struct {
PublicKey string `yaml:"public-key,omitempty"`
ShortId string `yaml:"short-id,omitempty"`
}
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"`
UdpOverTcp bool `yaml:"udp-over-tcp,omitempty"`
UdpOverTcpVersion string `yaml:"udp-over-tcp-version,omitempty"`
Plugin string `yaml:"plugin,omitempty"`
PluginOpts PluginOptsStruct `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 WSOptsStruct `yaml:"ws-opts,omitempty"`
AlterID string `yaml:"alterId,omitempty"`
GRPCOpts GRPCOptsStruct `yaml:"grpc-opts,omitempty"`
RealityOpts RealityOptsStruct `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"`
}

32
model/sub.go Normal file
View File

@ -0,0 +1,32 @@
package model
type Subscription struct {
Port int `yaml:"port,omitempty"`
SocksPort int `yaml:"socks-port,omitempty"`
AllowLan bool `yaml:"allow-lan,omitempty"`
Mode string `yaml:"mode,omitempty"`
LogLevel string `yaml:"log-level,omitempty"`
ExternalController string `yaml:"external-controller,omitempty"`
Proxies []Proxy `yaml:"proxies,omitempty"`
ProxyGroups []ProxyGroup `yaml:"proxy-groups,omitempty"`
Rules []string `yaml:"rules,omitempty"`
RuleProviders map[string]RuleProvider `yaml:"rule-providers,omitempty,omitempty"`
}
type ProxyGroup struct {
Name string `yaml:"name,omitempty"`
Type string `yaml:"type,omitempty"`
Proxies []string `yaml:"proxies,omitempty"`
}
type RuleProvider struct {
Type string `yaml:"type,omitempty"`
Behavior string `yaml:"behavior,omitempty"`
URL string `yaml:"url,omitempty"`
Path string `yaml:"path,omitempty"`
Interval int `yaml:"interval,omitempty"`
}
type Payload struct {
Rules []string `yaml:"payload,omitempty"`
}

13
parser/base64.go Normal file
View File

@ -0,0 +1,13 @@
package parser
import (
"encoding/base64"
)
func DecodeBase64(s string) (string, error) {
decodeStr, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", err
}
return string(decodeStr), nil
}

67
parser/ss.go Normal file
View File

@ -0,0 +1,67 @@
package parser
import (
"fmt"
"net/url"
"strconv"
"strings"
"sub/model"
)
// ParseSS 解析 SSShadowsocksURL
func ParseSS(proxy string) (model.Proxy, error) {
// 判断是否以 ss:// 开头
if !strings.HasPrefix(proxy, "ss://") {
return model.Proxy{}, fmt.Errorf("无效的 ss URL")
}
// 分割
parts := strings.SplitN(strings.TrimPrefix(proxy, "ss://"), "@", 2)
if len(parts) != 2 {
return model.Proxy{}, fmt.Errorf("无效的 ss URL")
}
if !strings.Contains(parts[0], ":") {
// 解码
decoded, err := DecodeBase64(parts[0])
if err != nil {
return model.Proxy{}, err
}
parts[0] = decoded
}
credentials := strings.SplitN(parts[0], ":", 2)
if len(credentials) != 2 {
return model.Proxy{}, fmt.Errorf("无效的 ss 凭证")
}
// 分割
serverInfo := strings.SplitN(parts[1], "#", 2)
serverAndPort := strings.SplitN(serverInfo[0], ":", 2)
if len(serverAndPort) != 2 {
return model.Proxy{}, fmt.Errorf("无效的 ss 服务器和端口")
}
// 转换端口字符串为数字
port, err := strconv.Atoi(strings.TrimSpace(serverAndPort[1]))
if err != nil {
return model.Proxy{}, err
}
// 返回结果
result := model.Proxy{
Type: "ss",
Cipher: strings.TrimSpace(credentials[0]),
Password: strings.TrimSpace(credentials[1]),
Server: strings.TrimSpace(serverAndPort[0]),
Port: port,
UDP: true,
Name: serverAndPort[0],
}
// 如果有节点名称
if len(serverInfo) == 2 {
unescape, err := url.QueryUnescape(serverInfo[1])
if err != nil {
return model.Proxy{}, err
}
result.Name = strings.TrimSpace(unescape)
} else {
result.Name = strings.TrimSpace(serverAndPort[0])
}
return result, nil
}

47
parser/ssr.go Normal file
View File

@ -0,0 +1,47 @@
package parser
import (
"fmt"
"net/url"
"strconv"
"strings"
"sub/model"
)
func ParseShadowsocksR(proxy string) (model.Proxy, error) {
// 判断是否以 ssr:// 开头
if !strings.HasPrefix(proxy, "ssr://") {
return model.Proxy{}, fmt.Errorf("无效的 ssr URL")
}
var err error
if !strings.Contains(proxy, ":") {
proxy, err = DecodeBase64(strings.TrimPrefix(proxy, "ssr://"))
if err != nil {
return model.Proxy{}, err
}
}
// 分割
detailsAndParams := strings.SplitN(strings.TrimPrefix(proxy, "ssr://"), "/?", 2)
parts := strings.Split(detailsAndParams[0], ":")
params, err := url.ParseQuery(detailsAndParams[1])
if err != nil {
return model.Proxy{}, err
}
// 处理端口
port, err := strconv.Atoi(parts[1])
if err != nil {
return model.Proxy{}, err
}
result := model.Proxy{
Type: "ssr",
Server: parts[0],
Port: port,
Protocol: parts[2],
Cipher: parts[3],
Obfs: parts[4],
Password: parts[5],
ObfsParam: params.Get("obfsparam"),
ProtocolParam: params.Get("protoparam"),
}
return result, nil
}

53
parser/trojan.go Normal file
View File

@ -0,0 +1,53 @@
package parser
import (
"fmt"
"net/url"
"strconv"
"strings"
"sub/model"
)
func ParseTrojan(proxy string) (model.Proxy, error) {
// 判断是否以 trojan:// 开头
if !strings.HasPrefix(proxy, "trojan://") {
return model.Proxy{}, fmt.Errorf("无效的 trojan URL")
}
// 分割
parts := strings.SplitN(strings.TrimPrefix(proxy, "trojan://"), "@", 2)
if len(parts) != 2 {
return model.Proxy{}, fmt.Errorf("无效的 trojan URL")
}
// 分割
serverInfo := strings.SplitN(parts[1], "#", 2)
serverAndPortAndParams := strings.SplitN(serverInfo[0], "?", 2)
serverAndPort := strings.SplitN(serverAndPortAndParams[0], ":", 2)
params, err := url.ParseQuery(serverAndPortAndParams[1])
if err != nil {
return model.Proxy{}, err
}
if len(serverAndPort) != 2 {
return model.Proxy{}, fmt.Errorf("无效的 trojan 服务器和端口")
}
// 处理端口
port, err := strconv.Atoi(strings.TrimSpace(serverAndPort[1]))
if err != nil {
return model.Proxy{}, err
}
// 返回结果
result := model.Proxy{
Type: "trojan",
Server: strings.TrimSpace(serverAndPort[0]),
Port: port,
UDP: true,
Password: strings.TrimSpace(parts[0]),
Sni: params.Get("sni"),
}
// 如果有节点名称
if len(serverInfo) == 2 {
result.Name, _ = url.QueryUnescape(strings.TrimSpace(serverInfo[1]))
} else {
result.Name = serverAndPort[0]
}
return result, nil
}

75
parser/vless.go Normal file
View File

@ -0,0 +1,75 @@
package parser
import (
"fmt"
"net/url"
"strconv"
"strings"
"sub/model"
)
func ParseVless(proxy string) (model.Proxy, error) {
// 判断是否以 vless:// 开头
if !strings.HasPrefix(proxy, "vless://") {
return model.Proxy{}, fmt.Errorf("无效的 vless URL")
}
// 分割
parts := strings.SplitN(strings.TrimPrefix(proxy, "vless://"), "@", 2)
if len(parts) != 2 {
return model.Proxy{}, fmt.Errorf("无效的 vless URL")
}
// 分割
serverInfo := strings.SplitN(parts[1], "#", 2)
serverAndPortAndParams := strings.SplitN(serverInfo[0], "?", 2)
serverAndPort := strings.SplitN(serverAndPortAndParams[0], ":", 2)
params, err := url.ParseQuery(serverAndPortAndParams[1])
if err != nil {
return model.Proxy{}, err
}
if len(serverAndPort) != 2 {
return model.Proxy{}, fmt.Errorf("无效的 vless 服务器和端口")
}
// 处理端口
port, err := strconv.Atoi(strings.TrimSpace(serverAndPort[1]))
if err != nil {
return model.Proxy{}, err
}
// 返回结果
result := model.Proxy{
Type: "vless",
Server: strings.TrimSpace(serverAndPort[0]),
Port: port,
UUID: strings.TrimSpace(parts[0]),
UDP: true,
Sni: params.Get("sni"),
Network: params.Get("type"),
TLS: params.Get("security") == "tls",
Flow: params.Get("flow"),
Fingerprint: params.Get("fp"),
Alpn: strings.Split(params.Get("alpn"), ","),
Servername: params.Get("sni"),
WSOpts: model.WSOptsStruct{
Path: params.Get("path"),
Headers: model.HeaderStruct{
Host: params.Get("host"),
},
},
GRPCOpts: model.GRPCOptsStruct{
GRPCServiceName: params.Get("serviceName"),
},
RealityOpts: model.RealityOptsStruct{
PublicKey: params.Get("pbk"),
},
}
// 如果有节点名称
if len(serverInfo) == 2 {
if strings.Contains(serverInfo[1], "|") {
result.Name = strings.SplitN(serverInfo[1], "|", 2)[1]
} else {
result.Name = serverInfo[1]
}
} else {
result.Name = serverAndPort[0]
}
return result, nil
}

68
parser/vmess.go Normal file
View File

@ -0,0 +1,68 @@
package parser
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"sub/model"
)
// vmess://eyJ2IjoiMiIsInBzIjoiXHU4MmYxXHU1NmZkLVx1NGYxOFx1NTMxNjMiLCJhZGQiOiJ0LmNjY2FvLmN5b3UiLCJwb3J0IjoiMTY2NDUiLCJpZCI6ImVmNmNiMGY0LTcwZWYtNDY2ZS04NGUwLWRiNDQwMWRmNmZhZiIsImFpZCI6IjAiLCJuZXQiOiJ3cyIsInR5cGUiOiJub25lIiwiaG9zdCI6IiIsInBhdGgiOiIiLCJ0bHMiOiIifQ==
func ParseVmess(proxy string) (model.Proxy, error) {
// 判断是否以 vmess:// 开头
if !strings.HasPrefix(proxy, "vmess://") {
return model.Proxy{}, fmt.Errorf("无效的 vmess URL")
}
// 解码
base64, err := DecodeBase64(strings.TrimPrefix(proxy, "vmess://"))
if err != nil {
return model.Proxy{}, errors.New("无效的 vmess URL")
}
// 解析
var vmess model.Vmess
err = json.Unmarshal([]byte(base64), &vmess)
if err != nil {
return model.Proxy{}, errors.New("无效的 vmess URL")
}
// 处理端口
port, err := strconv.Atoi(strings.TrimSpace(vmess.Port))
if err != nil {
return model.Proxy{}, errors.New("无效的 vmess URL")
}
if vmess.Scy == "" {
vmess.Scy = "auto"
}
if vmess.Net == "ws" && vmess.Path == "" {
vmess.Path = "/"
}
if vmess.Net == "ws" && vmess.Host == "" {
vmess.Host = vmess.Add
}
// 返回结果
result := model.Proxy{
Name: vmess.Ps,
Type: "vmess",
Server: vmess.Add,
Port: port,
UUID: vmess.Id,
AlterID: vmess.Aid,
Cipher: vmess.Scy,
UDP: true,
TLS: vmess.Tls == "tls",
Fingerprint: vmess.Fp,
ClientFingerprint: "chrome",
SkipCertVerify: true,
Servername: vmess.Add,
Network: vmess.Net,
WSOpts: model.WSOptsStruct{
Path: vmess.Path,
Headers: model.HeaderStruct{
Host: vmess.Host,
},
},
}
return result, nil
}

23
utils/get.go Normal file
View File

@ -0,0 +1,23 @@
package utils
import (
"net/http"
"time"
)
func GetWithRetry(url string) (resp *http.Response, err error) {
retryTimes := 3
haveTried := 0
retryDelay := time.Second // 延迟1秒再重试
for haveTried < retryTimes {
get, err := http.Get(url)
if err != nil {
haveTried++
time.Sleep(retryDelay)
continue
} else {
return get, nil
}
}
return nil, err
}

105
utils/proxy.go Normal file
View File

@ -0,0 +1,105 @@
package utils
import (
"sort"
"strings"
"sub/model"
"sub/parser"
)
func GetContryCode(proxy model.Proxy) string {
keys := make([]string, 0, len(model.CountryKeywords))
for k := range model.CountryKeywords {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
if strings.Contains(strings.ToLower(proxy.Name), strings.ToLower(k)) {
return model.CountryKeywords[k]
}
}
return "其他地区"
}
var skipGroups = map[string]bool{
"手动切换": true,
"全球直连": true,
"广告拦截": true,
"应用进化": true,
}
func AddProxy(sub *model.Subscription, proxies ...model.Proxy) {
newContryNames := make([]string, 0, len(proxies))
for p := range proxies {
proxy := proxies[p]
sub.Proxies = append(sub.Proxies, proxy)
haveProxyGroup := false
for i := range sub.ProxyGroups {
group := &sub.ProxyGroups[i]
groupName := []rune(group.Name)
proxyName := []rune(proxy.Name)
if string(groupName[:2]) == string(proxyName[:2]) || GetContryCode(proxy) == group.Name {
group.Proxies = append(group.Proxies, proxy.Name)
haveProxyGroup = true
}
if group.Name == "手动切换" {
group.Proxies = append(group.Proxies, proxy.Name)
}
}
if !haveProxyGroup {
contryCode := GetContryCode(proxy)
newGroup := model.ProxyGroup{
Name: contryCode,
Type: "select",
Proxies: []string{proxy.Name},
}
newContryNames = append(newContryNames, contryCode)
sub.ProxyGroups = append(sub.ProxyGroups, newGroup)
}
}
newContryNamesMap := make(map[string]bool)
for _, n := range newContryNames {
newContryNamesMap[n] = true
}
for i := range sub.ProxyGroups {
if !skipGroups[sub.ProxyGroups[i].Name] && !newContryNamesMap[sub.ProxyGroups[i].Name] {
newProxies := make(
[]string, len(newContryNames), len(newContryNames)+len(sub.ProxyGroups[i].Proxies),
)
copy(newProxies, newContryNames)
sub.ProxyGroups[i].Proxies = append(newProxies, sub.ProxyGroups[i].Proxies...)
}
}
}
func ParseProxy(proxies ...string) []model.Proxy {
var result []model.Proxy
for _, proxy := range proxies {
if proxy != "" {
var proxyItem model.Proxy
var err error
// 解析节点
if strings.HasPrefix(proxy, "ss://") {
proxyItem, err = parser.ParseSS(proxy)
}
if strings.HasPrefix(proxy, "trojan://") {
proxyItem, err = parser.ParseTrojan(proxy)
}
if strings.HasPrefix(proxy, "vmess://") {
proxyItem, err = parser.ParseVmess(proxy)
}
if strings.HasPrefix(proxy, "vless://") {
proxyItem, err = parser.ParseVless(proxy)
}
if strings.HasPrefix(proxy, "ssr://") {
proxyItem, err = parser.ParseShadowsocksR(proxy)
}
if err == nil {
result = append(result, proxyItem)
}
}
}
return result
}

54
utils/rule.go Normal file
View File

@ -0,0 +1,54 @@
package utils
import (
"fmt"
"gopkg.in/yaml.v3"
"io"
"sub/model"
)
func AddRulesByUrl(sub *model.Subscription, url string, proxy string) {
get, err := GetWithRetry(url)
if err != nil {
fmt.Println(err)
return
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
fmt.Println(err)
}
}(get.Body)
bytes, err := io.ReadAll(get.Body)
if err != nil {
fmt.Println(err)
return
}
var payload model.Payload
err = yaml.Unmarshal(bytes, &payload)
if err != nil {
fmt.Println(err)
return
}
for i := range payload.Rules {
payload.Rules[i] = payload.Rules[i] + "," + proxy
}
AddRules(sub, payload.Rules...)
}
func AddRuleProvider(
sub *model.Subscription, providerName string, proxy string, provider model.RuleProvider,
) {
if sub.RuleProviders == nil {
sub.RuleProviders = make(map[string]model.RuleProvider)
}
sub.RuleProviders[providerName] = provider
AddRules(
sub,
fmt.Sprintf("RULE-SET,%s,%s", providerName, proxy),
)
}
func AddRules(sub *model.Subscription, rules ...string) {
sub.Rules = append(rules, sub.Rules...)
}

85
utils/sub.go Normal file
View File

@ -0,0 +1,85 @@
package utils
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"time"
)
var subsDir = "subs"
func LoadSubscription(url string, refresh bool) ([]byte, error) {
if refresh {
return FetchSubscriptionFromAPI(url)
}
hash := md5.Sum([]byte(url))
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:])+".yaml")
const refreshInterval = 5 * 60 // 5分钟
stat, err := os.Stat(fileName)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
return FetchSubscriptionFromAPI(url)
}
lastGetTime := stat.ModTime().Unix() // 单位是秒
if lastGetTime+refreshInterval > time.Now().Unix() {
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Println(err)
}
}(file)
subContent, err := io.ReadAll(file)
if err != nil {
return nil, err
}
return subContent, nil
}
return FetchSubscriptionFromAPI(url)
}
func FetchSubscriptionFromAPI(url string) ([]byte, error) {
hash := md5.Sum([]byte(url))
fileName := filepath.Join(subsDir, hex.EncodeToString(hash[:])+".yaml")
resp, err := GetWithRetry(url)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
fmt.Println(err)
}
}(resp.Body)
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
file, err := os.Create(fileName)
if err != nil {
return nil, err
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Println(err)
}
}(file)
_, err = file.Write(data)
if err != nil {
return nil, fmt.Errorf("failed to write to sub.yaml: %w", err)
}
if err != nil {
return nil, fmt.Errorf("failed to unmarshal yaml: %w", err)
}
return data, nil
}

36
utils/template.go Normal file
View File

@ -0,0 +1,36 @@
package utils
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
)
// LoadTemplate 加载模板
// template 模板文件名
func LoadTemplate(template string) (string, error) {
tPath := filepath.Join("templates", template)
if _, err := os.Stat(tPath); err == nil {
file, err := os.Open(tPath)
if err != nil {
return "", err
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Println(err)
}
}(file)
result, err := io.ReadAll(file)
if err != nil {
return "", err
}
if err != nil {
return "", err
}
return string(result), nil
}
return "", errors.New("模板文件不存在")
}

7
validator/sub.go Normal file
View File

@ -0,0 +1,7 @@
package validator
type SubQuery struct {
Sub string `form:"sub" json:"name" binding:"required"`
Mix bool `form:"mix,default=false" json:"email" binding:""`
Refresh bool `form:"refresh,default=false" json:"age" binding:""`
}