Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b05dd37500 | ||
|
|
7fabd3c3e2 | ||
|
|
6dc20398ae | ||
|
|
03118a24a3 | ||
|
|
0cb7c9f948 | ||
|
|
824656f9d0 | ||
|
|
e3d56ae9b7 | ||
|
|
794ba22232 |
39
CHANGELOG.md
39
CHANGELOG.md
@@ -1,5 +1,44 @@
|
||||
# 更新日志
|
||||
|
||||
v1.5.0
|
||||
---
|
||||
- CHANGE: 优化代码结构,提升性能
|
||||
- CHANGE: 改进核心部分,即proxy模块的转发部分,对请求体处理与响应体处理进行优化
|
||||
- CHANGE: 配置文件格式由yaml切换至toml,使其具备更好的可读性
|
||||
- ADD: 黑白名单引入通配符支持,支持完全屏蔽或放行某个用户,例如`onwer/*`表示匹配`owner`的所有仓库
|
||||
- ADD: 新增API模块,新增配置开关状态接口,以在前端指示功能状态
|
||||
- CHANGE: 由于API变动,对前端进行相应调整
|
||||
- ADD: 日志模块引入日志级别,排障更加直观
|
||||
- CHANGE: 改进黑白名单机制,若禁用相关功能,则不对相关模块进行初始化
|
||||
|
||||
24w15d
|
||||
---
|
||||
- PRE-RELEASE: 此版本是v1.5.0的预发布版本,请勿在生产环境中使用
|
||||
- CHANGE: 优化代码结构,提升性能
|
||||
- ADD: 新增API模块,新增配置开关状态接口,以在前端指示功能状态
|
||||
- CHANGE: 由于API变动,对前端进行相应调整
|
||||
|
||||
24w15c
|
||||
---
|
||||
- PRE-RELEASE: 此版本是v1.5.0的预发布版本,请勿在生产环境中使用
|
||||
- CHANGE: 优化代码结构,提升性能
|
||||
- CHANGE: 改进核心部分,即proxy模块的转发部分,对请求体处理与响应体处理进行优化
|
||||
- CHANGE: 改进黑白名单机制,若禁用相关功能,则不对对应模块进行初始化
|
||||
- ADD: 黑白名单引入通配符支持,支持完全屏蔽或放行某个用户,例如`onwer/*`表示匹配`owner`的所有仓库
|
||||
- ADD: 日志模块引入日志级别,排障更加直观
|
||||
|
||||
24w15b
|
||||
---
|
||||
- PRE-RELEASE: 此版本是v1.5.0的预发布版本,请勿在生产环境中使用
|
||||
- CHANGE: 优化代码结构,提升性能
|
||||
- FIX: 修正24w15a版本的部分问题
|
||||
|
||||
24w15a
|
||||
---
|
||||
- PRE-RELEASE: 此版本是v1.5.0的预发布版本,请勿在生产环境中使用
|
||||
- CHANGE: 优化代码结构,提升性能
|
||||
- CHANGE: 将配置文件由yaml切换至toml
|
||||
|
||||
v1.4.3
|
||||
---
|
||||
- CHANGE: 优化代码结构,提升性能
|
||||
|
||||
@@ -1 +1 @@
|
||||
24w15b
|
||||
24w15d
|
||||
58
README.md
58
README.md
@@ -16,7 +16,7 @@
|
||||
- 支持Docker部署
|
||||
- 支持速率限制
|
||||
- 支持用户鉴权
|
||||
- 支持自定义黑名单
|
||||
- 支持自定义黑名单/白名单
|
||||
- 符合[RFC 7234](https://httpwg.org/specs/rfc7234.html)的HTTP Cache
|
||||
- 使用Caddy作为Web Server
|
||||
- 基于[WJQSERVER-STUDIO/golang-temp](https://github.com/WJQSERVER-STUDIO/golang-temp)模板构建,具有标准化的日志记录与构建流程
|
||||
@@ -60,39 +60,33 @@ docker run -p 7210:80 -v ./ghproxy/log/run:/data/ghproxy/log -v ./ghproxy/log/ca
|
||||
|
||||
### 外部配置文件
|
||||
|
||||
本项目采用config.yaml作为外部配置,默认配置如下
|
||||
使用Docker部署时,慎重修改config.yaml,以免造成不必要的麻烦
|
||||
本项目采用`config.toml`作为外部配置,默认配置如下
|
||||
使用Docker部署时,慎重修改`config.toml`,以免造成不必要的麻烦
|
||||
|
||||
```yaml
|
||||
# 核心配置
|
||||
server:
|
||||
port: 8080 # 监听端口(小白请勿修改)
|
||||
host: "127.0.0.1" # 监听地址(小白请勿修改)
|
||||
sizelimit: 131072000 # 125MB
|
||||
```toml
|
||||
[server]
|
||||
host = "127.0.0.1" # 监听地址(小白请勿修改)
|
||||
port = 8080 #监听端口(小白请勿修改)
|
||||
sizelimit = 131072000 # 125MB
|
||||
|
||||
# 日志配置
|
||||
logger:
|
||||
logfilepath: "/data/ghproxy/log/ghproxy.log" # 日志文件路径(小白请勿修改)
|
||||
maxlogsize: 5 # MB
|
||||
[log]
|
||||
logfilepath = "/data/ghproxy/log/ghproxy.log" # 日志文件路径(小白请勿修改)
|
||||
maxlogsize = 5 # MB
|
||||
|
||||
# CORS 配置
|
||||
cors:
|
||||
enabled: true # 是否开启CORS
|
||||
[cors]
|
||||
enabled = true # 是否开启CORS
|
||||
|
||||
# 鉴权配置
|
||||
auth:
|
||||
enabled: false # 是否开启鉴权
|
||||
authtoken: "test" # 鉴权Token
|
||||
[auth]
|
||||
authtoken = "test" # 鉴权Token
|
||||
enabled = false # 是否开启鉴权
|
||||
|
||||
# 黑名单配置
|
||||
blacklist:
|
||||
enabled: true # 是否开启黑名单
|
||||
blacklistfile: "/data/ghproxy/config/blacklist.json"
|
||||
[blacklist]
|
||||
blacklistfile = "/data/ghproxy/config/blacklist.json" # 黑名单文件路径
|
||||
enabled = false # 是否开启黑名单
|
||||
|
||||
# 白名单配置
|
||||
whitelist:
|
||||
enabled: false # 是否开启白名单
|
||||
whitelistfile: "/data/ghproxy/config/whitelist.json"
|
||||
[whitelist]
|
||||
enabled = false # 是否开启白名单
|
||||
whitelistfile = "/data/ghproxy/config/whitelist.json" # 白名单文件路径
|
||||
|
||||
```
|
||||
|
||||
@@ -105,7 +99,7 @@ whitelist:
|
||||
"blacklist": [
|
||||
"test/test1",
|
||||
"example/repo2",
|
||||
"another/repo3"
|
||||
"another/*"
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -119,7 +113,7 @@ whitelist:
|
||||
"whitelist": [
|
||||
"test/test1",
|
||||
"example/repo2",
|
||||
"another/repo3"
|
||||
"another/*"
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -139,6 +133,10 @@ example.com {
|
||||
}
|
||||
```
|
||||
|
||||
### 前端页面
|
||||
|
||||

|
||||
|
||||
## TODO & DEV
|
||||
|
||||
### TODO
|
||||
|
||||
76
api/api.go
Normal file
76
api/api.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"ghproxy/config"
|
||||
"ghproxy/logger"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var (
|
||||
router *gin.Engine
|
||||
cfg *config.Config
|
||||
)
|
||||
|
||||
// 日志模块
|
||||
var (
|
||||
logw = logger.Logw
|
||||
logInfo = logger.LogInfo
|
||||
LogWarning = logger.LogWarning
|
||||
logError = logger.LogError
|
||||
)
|
||||
|
||||
func InitHandleRouter(cfg *config.Config, router *gin.Engine) {
|
||||
// 设置路由
|
||||
apiRouter := router.Group("api")
|
||||
{
|
||||
apiRouter.GET("/size_limit", func(c *gin.Context) {
|
||||
SizeLimitHandler(cfg, c)
|
||||
})
|
||||
apiRouter.GET("/whitelist/status", func(c *gin.Context) {
|
||||
WhiteListStatusHandler(c, cfg)
|
||||
})
|
||||
apiRouter.GET("/blacklist/status", func(c *gin.Context) {
|
||||
BlackListStatusHandler(c, cfg)
|
||||
})
|
||||
apiRouter.GET("/healthcheck", func(c *gin.Context) {
|
||||
HealthcheckHandler(c)
|
||||
})
|
||||
}
|
||||
logInfo("API router Init success")
|
||||
}
|
||||
|
||||
func SizeLimitHandler(cfg *config.Config, c *gin.Context) {
|
||||
// 转换为MB
|
||||
sizeLimit := cfg.Server.SizeLimit / 1024 / 1024
|
||||
// 设置响应头
|
||||
c.Writer.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(c.Writer).Encode(map[string]interface{}{
|
||||
"MaxResponseBodySize": sizeLimit,
|
||||
})
|
||||
}
|
||||
|
||||
func WhiteListStatusHandler(c *gin.Context, cfg *config.Config) {
|
||||
// 设置响应头
|
||||
c.Writer.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(c.Writer).Encode(map[string]interface{}{
|
||||
"Whitelist": cfg.Whitelist.Enabled,
|
||||
})
|
||||
}
|
||||
|
||||
func BlackListStatusHandler(c *gin.Context, cfg *config.Config) {
|
||||
// 设置响应头
|
||||
c.Writer.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(c.Writer).Encode(map[string]interface{}{
|
||||
"Blacklist": cfg.Blacklist.Enabled,
|
||||
})
|
||||
}
|
||||
|
||||
func HealthcheckHandler(c *gin.Context) {
|
||||
// 设置响应头
|
||||
c.Writer.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(c.Writer).Encode(map[string]interface{}{
|
||||
"Status": "OK",
|
||||
})
|
||||
}
|
||||
27
auth/auth.go
27
auth/auth.go
@@ -7,7 +7,24 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var logw = logger.Logw
|
||||
// 日志模块
|
||||
var (
|
||||
logw = logger.Logw
|
||||
logInfo = logger.LogInfo
|
||||
LogWarning = logger.LogWarning
|
||||
logError = logger.LogError
|
||||
)
|
||||
|
||||
// Auth Init
|
||||
func Init(cfg *config.Config) {
|
||||
if cfg.Blacklist.Enabled {
|
||||
LoadBlacklist(cfg)
|
||||
}
|
||||
if cfg.Whitelist.Enabled {
|
||||
LoadWhitelist(cfg)
|
||||
}
|
||||
logInfo("Auth Init")
|
||||
}
|
||||
|
||||
func AuthHandler(c *gin.Context, cfg *config.Config) bool {
|
||||
// 如果身份验证未启用,直接返回 true
|
||||
@@ -17,19 +34,19 @@ func AuthHandler(c *gin.Context, cfg *config.Config) bool {
|
||||
|
||||
// 获取 auth_token 参数
|
||||
authToken := c.Query("auth_token")
|
||||
logw("auth_token received: %s", authToken)
|
||||
logInfo("auth_token received: %s", authToken)
|
||||
|
||||
// 验证 token
|
||||
if authToken == "" {
|
||||
logw("auth FAILED: no auth_token provided")
|
||||
LogWarning("auth FAILED: no auth_token provided")
|
||||
return false
|
||||
}
|
||||
|
||||
isValid := authToken == cfg.Auth.AuthToken
|
||||
if !isValid {
|
||||
logw("auth FAILED: invalid auth_token: %s", authToken)
|
||||
LogWarning("auth FAILED: invalid auth_token: %s", authToken)
|
||||
}
|
||||
|
||||
logw("auth SUCCESS: %t", isValid)
|
||||
logInfo("auth SUCCESS: %t", isValid)
|
||||
return isValid
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"ghproxy/config"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type BlacklistConfig struct {
|
||||
@@ -22,22 +23,32 @@ func LoadBlacklist(cfg *config.Config) {
|
||||
|
||||
data, err := os.ReadFile(blacklistfile)
|
||||
if err != nil {
|
||||
logw("Failed to read blacklist file: %v", err)
|
||||
logError("Failed to read blacklist file: %v", err)
|
||||
}
|
||||
|
||||
err = json.Unmarshal(data, blacklist)
|
||||
if err != nil {
|
||||
logw("Failed to unmarshal blacklist JSON: %v", err)
|
||||
logError("Failed to unmarshal blacklist JSON: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// fullrepo: "owner/repo" or "owner/*"
|
||||
func CheckBlacklist(fullrepo string) bool {
|
||||
return forRangeCheckBlacklist(blacklist.Blacklist, fullrepo)
|
||||
}
|
||||
|
||||
func sliceRepoName_Blacklist(fullrepo string) (string, string) {
|
||||
s := strings.Split(fullrepo, "/")
|
||||
if len(s) != 2 {
|
||||
return "", ""
|
||||
}
|
||||
return s[0], s[1]
|
||||
}
|
||||
|
||||
func forRangeCheckBlacklist(blist []string, fullrepo string) bool {
|
||||
repoUser, _ := sliceRepoName_Blacklist(fullrepo)
|
||||
for _, blocked := range blist {
|
||||
if blocked == fullrepo {
|
||||
if blocked == fullrepo || (strings.HasSuffix(blocked, "/*") && strings.HasPrefix(repoUser, blocked[:len(blocked)-2])) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"ghproxy/config"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type WhitelistConfig struct {
|
||||
@@ -21,12 +22,12 @@ func LoadWhitelist(cfg *config.Config) {
|
||||
|
||||
data, err := os.ReadFile(whitelistfile)
|
||||
if err != nil {
|
||||
logw("Failed to read whitelist file: %v", err)
|
||||
logError("Failed to read whitelist file: %v", err)
|
||||
}
|
||||
|
||||
err = json.Unmarshal(data, whitelist)
|
||||
if err != nil {
|
||||
logw("Failed to unmarshal whitelist JSON: %v", err)
|
||||
logError("Failed to unmarshal whitelist JSON: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,9 +35,18 @@ func CheckWhitelist(fullrepo string) bool {
|
||||
return forRangeCheckWhitelist(whitelist.Whitelist, fullrepo)
|
||||
}
|
||||
|
||||
func forRangeCheckWhitelist(blist []string, fullrepo string) bool {
|
||||
for _, blocked := range blist {
|
||||
if blocked == fullrepo {
|
||||
func sliceRepoName_Whitelist(fullrepo string) (string, string) {
|
||||
s := strings.Split(fullrepo, "/")
|
||||
if len(s) != 2 {
|
||||
return "", ""
|
||||
}
|
||||
return s[0], s[1]
|
||||
}
|
||||
|
||||
func forRangeCheckWhitelist(wlist []string, fullrepo string) bool {
|
||||
repoUser, _ := sliceRepoName_Whitelist(fullrepo)
|
||||
for _, blocked := range wlist {
|
||||
if blocked == fullrepo || (strings.HasSuffix(blocked, "/*") && strings.HasPrefix(repoUser, blocked[:len(blocked)-2])) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
{
|
||||
"blacklist": [
|
||||
"black/list",
|
||||
"test/test1",
|
||||
"example/repo2"
|
||||
]
|
||||
}
|
||||
|
||||
"blacklist": [
|
||||
"black/list",
|
||||
"test/test1",
|
||||
"example/repo2"
|
||||
]
|
||||
}
|
||||
@@ -56,7 +56,7 @@ func loadYAML(filePath string, out interface{}) error {
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig
|
||||
Log LoggerConfig
|
||||
Log LogConfig
|
||||
CORS CORSConfig
|
||||
Auth AuthConfig
|
||||
Blacklist BlacklistConfig
|
||||
@@ -69,7 +69,7 @@ type ServerConfig struct {
|
||||
SizeLimit int `toml:"sizelimit"`
|
||||
}
|
||||
|
||||
type LoggerConfig struct {
|
||||
type LogConfig struct {
|
||||
LogFilePath string `toml:"logfilepath"`
|
||||
MaxLogSize int `toml:"maxlogsize"`
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ host = "127.0.0.1"
|
||||
port = 8080
|
||||
sizelimit = 131072000 # 125MB
|
||||
|
||||
[logger]
|
||||
[log]
|
||||
logfilepath = "/data/ghproxy/log/ghproxy.log"
|
||||
maxlogsize = 5 # MB
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
{
|
||||
"whitelist": [
|
||||
"white/list",
|
||||
"white/test1",
|
||||
"example/white"
|
||||
]
|
||||
}
|
||||
|
||||
"whitelist": [
|
||||
"white/list",
|
||||
"white/test1",
|
||||
"example/white"
|
||||
]
|
||||
}
|
||||
@@ -26,7 +26,7 @@ RUN wget -O /usr/local/bin/init.sh https://raw.githubusercontent.com/${USER}/${R
|
||||
|
||||
# 拉取配置
|
||||
RUN wget -O /data/caddy/Caddyfile https://raw.githubusercontent.com/${USER}/${REPO}/main/caddyfile/release/Caddyfile
|
||||
RUN wget -O /data/${APPLICATION}/config.yaml https://raw.githubusercontent.com/${USER}/${REPO}/main/config/config.yaml
|
||||
RUN wget -O /data/${APPLICATION}/config.toml https://raw.githubusercontent.com/${USER}/${REPO}/main/config/config.toml
|
||||
RUN wget -O /data/${APPLICATION}/blacklist.json https://raw.githubusercontent.com/${USER}/${REPO}/main/config/blacklist.json
|
||||
RUN wget -O /data/${APPLICATION}/whitelist.json https://raw.githubusercontent.com/${USER}/${REPO}/main/config/whitelist.json
|
||||
|
||||
|
||||
@@ -14,13 +14,13 @@ if [ ! -f /data/${APPLICATION}/config/whitelist.json ]; then
|
||||
cp /data/${APPLICATION}/whitelist.json /data/${APPLICATION}/config/whitelist.json
|
||||
fi
|
||||
|
||||
if [ ! -f /data/${APPLICATION}/config/config.yaml ]; then
|
||||
cp /data/${APPLICATION}/config.yaml /data/${APPLICATION}/config/config.yaml
|
||||
if [ ! -f /data/${APPLICATION}/config/config.toml ]; then
|
||||
cp /data/${APPLICATION}/config.toml /data/${APPLICATION}/config/config.toml
|
||||
fi
|
||||
|
||||
/data/caddy/caddy run --config /data/caddy/config/Caddyfile > /data/${APPLICATION}/log/caddy.log 2>&1 &
|
||||
|
||||
/data/${APPLICATION}/${APPLICATION} -cfg /data/${APPLICATION}/config/config.yaml > /data/${APPLICATION}/log/run.log 2>&1 &
|
||||
/data/${APPLICATION}/${APPLICATION} -cfg /data/${APPLICATION}/config/config.toml > /data/${APPLICATION}/log/run.log 2>&1 &
|
||||
|
||||
while true; do
|
||||
sleep 1
|
||||
|
||||
14
go.mod
14
go.mod
@@ -3,17 +3,17 @@ module ghproxy
|
||||
go 1.23.2
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.4.0
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/imroc/req/v3 v3.46.1
|
||||
github.com/imroc/req/v3 v3.47.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.4.0 // indirect
|
||||
github.com/andybalholm/brotli v1.1.0 // indirect
|
||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||
github.com/bytedance/sonic v1.12.3 // indirect
|
||||
github.com/bytedance/sonic/loader v0.2.0 // indirect
|
||||
github.com/cloudflare/circl v1.4.0 // indirect
|
||||
github.com/cloudflare/circl v1.5.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.5 // indirect
|
||||
@@ -23,11 +23,11 @@ require (
|
||||
github.com/go-playground/validator/v10 v10.22.1 // indirect
|
||||
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
|
||||
github.com/goccy/go-json v0.10.3 // indirect
|
||||
github.com/google/pprof v0.0.0-20241008150032-332c0e1a4a34 // indirect
|
||||
github.com/google/pprof v0.0.0-20241009165004-a3522334989c // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.17.10 // indirect
|
||||
github.com/klauspost/compress v1.17.11 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
@@ -43,7 +43,7 @@ require (
|
||||
go.uber.org/mock v0.4.0 // indirect
|
||||
golang.org/x/arch v0.11.0 // indirect
|
||||
golang.org/x/crypto v0.28.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20241004190924-225e2abe05e6 // indirect
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c // indirect
|
||||
golang.org/x/mod v0.21.0 // indirect
|
||||
golang.org/x/net v0.30.0 // indirect
|
||||
golang.org/x/sync v0.8.0 // indirect
|
||||
|
||||
13
go.sum
13
go.sum
@@ -2,6 +2,8 @@ github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0
|
||||
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
|
||||
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
|
||||
github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA=
|
||||
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic v1.12.3 h1:W2MGa7RCU1QTeYRTPE3+88mVC0yXmsRQRChiyVocVjU=
|
||||
@@ -12,6 +14,8 @@ github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP
|
||||
github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/cloudflare/circl v1.4.0 h1:BV7h5MgrktNzytKmWjpOtdYrf0lkkbF8YMlBGPhJQrY=
|
||||
github.com/cloudflare/circl v1.4.0/go.mod h1:PDRU+oXvdD7KCtgKxW95M5Z8BpSCJXQORiZFnBQS5QU=
|
||||
github.com/cloudflare/circl v1.5.0 h1:hxIWksrX6XN5a1L2TI/h53AGPhNHoUBo+TD1ms9+pys=
|
||||
github.com/cloudflare/circl v1.5.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
@@ -46,6 +50,8 @@ github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134 h1:c5FlPPgxOn7kJz3VoP
|
||||
github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
|
||||
github.com/google/pprof v0.0.0-20241008150032-332c0e1a4a34 h1:4iExbL0TFWhkSCZx6nfKwjM+CbnBySx18KssYmdL1fc=
|
||||
github.com/google/pprof v0.0.0-20241008150032-332c0e1a4a34/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
|
||||
github.com/google/pprof v0.0.0-20241009165004-a3522334989c h1:NDovD0SMpBYXlE1zJmS1q55vWB/fUQBcPAqAboZSccA=
|
||||
github.com/google/pprof v0.0.0-20241009165004-a3522334989c/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
@@ -53,12 +59,16 @@ github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+l
|
||||
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||
github.com/imroc/req/v3 v3.46.1 h1:oahr2hBTb3AaFI4P6jkN0Elj2ZVKJcdQ/IjWqeIKjvc=
|
||||
github.com/imroc/req/v3 v3.46.1/go.mod h1:weam9gmyb00QnOtu6HXSnk44dNFkIUQb5QdMx13FeUU=
|
||||
github.com/imroc/req/v3 v3.47.0 h1:O8D1KtZSEuhHIrWA+YBd4MZeFg3KprfbNSFR49EWdNA=
|
||||
github.com/imroc/req/v3 v3.47.0/go.mod h1:weam9gmyb00QnOtu6HXSnk44dNFkIUQb5QdMx13FeUU=
|
||||
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/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
|
||||
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||
github.com/klauspost/compress v1.17.10 h1:oXAz+Vh0PMUvJczoi+flxpnBEPxoER1IaAnU/NMPtT0=
|
||||
github.com/klauspost/compress v1.17.10/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
@@ -102,6 +112,7 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
|
||||
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=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
|
||||
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
@@ -119,6 +130,8 @@ golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWB
|
||||
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY=
|
||||
golang.org/x/exp v0.0.0-20241004190924-225e2abe05e6 h1:1wqE9dj9NpSm04INVsJhhEUzhuDVjbcyKH91sVyPATw=
|
||||
golang.org/x/exp v0.0.0-20241004190924-225e2abe05e6/go.mod h1:NQtJDoLvd6faHhE7m4T/1IY708gDefGGjR/iUW8yQQ8=
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c h1:7dEasQXItcW1xKJ2+gg5VOiBnqWrJc+rq0DPKyvvdbY=
|
||||
golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c/go.mod h1:NQtJDoLvd6faHhE7m4T/1IY708gDefGGjR/iUW8yQQ8=
|
||||
golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=
|
||||
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||
|
||||
@@ -19,14 +19,16 @@ var (
|
||||
logChannel = make(chan string, 100)
|
||||
quitChannel = make(chan struct{})
|
||||
logFileMutex sync.Mutex // 保护 logFile 的互斥锁
|
||||
logFilePath = "/data/ghproxy/log/ghproxy.log"
|
||||
)
|
||||
|
||||
// Init 初始化日志记录器,接受日志文件路径作为参数
|
||||
func Init(logFilePath string, maxLogsize int) error {
|
||||
func Init(logFilePath_input string, maxLogsize int) error {
|
||||
logFileMutex.Lock()
|
||||
defer logFileMutex.Unlock()
|
||||
|
||||
var err error
|
||||
logFilePath = logFilePath_input
|
||||
logFile, err = os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -62,6 +64,26 @@ func Logw(format string, args ...interface{}) {
|
||||
Log(message)
|
||||
}
|
||||
|
||||
// 日志等级INFO
|
||||
func LogInfo(format string, args ...interface{}) {
|
||||
message := fmt.Sprintf(format, args...)
|
||||
output := fmt.Sprintf("[INFO] %s", message)
|
||||
Log(output)
|
||||
}
|
||||
|
||||
// 日志等级WARNING
|
||||
func LogWarning(format string, args ...interface{}) {
|
||||
message := fmt.Sprintf(format, args...)
|
||||
output := fmt.Sprintf("[WARNING] %s", message)
|
||||
Log(output)
|
||||
}
|
||||
|
||||
// 日志等级ERROR
|
||||
func LogError(format string, args ...interface{}) {
|
||||
message := fmt.Sprintf(format, args...)
|
||||
Log(message)
|
||||
}
|
||||
|
||||
// Close 关闭日志文件
|
||||
func Close() {
|
||||
logFileMutex.Lock()
|
||||
|
||||
48
main.go
48
main.go
@@ -1,12 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"ghproxy/api"
|
||||
"ghproxy/auth"
|
||||
"ghproxy/config"
|
||||
"ghproxy/logger"
|
||||
@@ -17,9 +17,16 @@ import (
|
||||
|
||||
var (
|
||||
cfg *config.Config
|
||||
logw = logger.Logw
|
||||
router *gin.Engine
|
||||
configfile = "/data/ghproxy/config/config.yaml"
|
||||
configfile = "/data/ghproxy/config/config.toml"
|
||||
)
|
||||
|
||||
// 日志模块
|
||||
var (
|
||||
logw = logger.Logw
|
||||
logInfo = logger.LogInfo
|
||||
LogWarning = logger.LogWarning
|
||||
logError = logger.LogError
|
||||
)
|
||||
|
||||
func ReadFlag() {
|
||||
@@ -37,26 +44,30 @@ func loadConfig() {
|
||||
fmt.Printf("Loaded config: %v\n", cfg)
|
||||
}
|
||||
|
||||
func setupLogger() {
|
||||
func setupLogger(cfg *config.Config) {
|
||||
// 初始化日志模块
|
||||
var err error
|
||||
err = logger.Init(cfg.Log.LogFilePath, cfg.Log.MaxLogSize) // 传递日志文件路径
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to initialize logger: %v", err)
|
||||
}
|
||||
logw("Logger initialized")
|
||||
logw("Init Completed")
|
||||
logInfo("Logger initialized")
|
||||
logInfo("Init Completed")
|
||||
}
|
||||
|
||||
func Loadlist(cfg *config.Config) {
|
||||
auth.LoadBlacklist(cfg)
|
||||
auth.LoadWhitelist(cfg)
|
||||
auth.Init(cfg)
|
||||
}
|
||||
|
||||
func setupApi(cfg *config.Config, router *gin.Engine) {
|
||||
// 注册 API 接口
|
||||
api.InitHandleRouter(cfg, router)
|
||||
}
|
||||
|
||||
func init() {
|
||||
ReadFlag()
|
||||
loadConfig()
|
||||
setupLogger()
|
||||
setupLogger(cfg)
|
||||
Loadlist(cfg)
|
||||
|
||||
// 设置 Gin 模式
|
||||
@@ -65,18 +76,13 @@ func init() {
|
||||
// 初始化路由
|
||||
router = gin.Default()
|
||||
|
||||
setupApi(cfg, router)
|
||||
|
||||
// 定义路由
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
c.Redirect(http.StatusMovedPermanently, "https://ghproxy0rtt.1888866.xyz/")
|
||||
})
|
||||
|
||||
router.GET("/api", api)
|
||||
|
||||
// 健康检查
|
||||
router.GET("/api/healthcheck", func(c *gin.Context) {
|
||||
c.String(http.StatusOK, "OK")
|
||||
})
|
||||
|
||||
// 未匹配路由处理
|
||||
router.NoRoute(func(c *gin.Context) {
|
||||
proxy.NoRouteHandler(cfg)(c)
|
||||
@@ -87,16 +93,8 @@ func main() {
|
||||
// 启动服务器
|
||||
err := router.Run(fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port))
|
||||
if err != nil {
|
||||
log.Fatalf("Error starting server: %v\n", err)
|
||||
logError("Error starting server: %v\n", err)
|
||||
}
|
||||
|
||||
fmt.Println("Program finished")
|
||||
}
|
||||
|
||||
func api(c *gin.Context) {
|
||||
// 设置响应头
|
||||
c.Writer.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(c.Writer).Encode(map[string]interface{}{
|
||||
"MaxResponseBodySize": cfg.Server.SizeLimit,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -91,6 +91,18 @@
|
||||
|
||||
}
|
||||
|
||||
.status-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.status-container p {
|
||||
margin: 0px 5px;
|
||||
}
|
||||
|
||||
|
||||
.code {
|
||||
position: relative;
|
||||
padding-right: 0px;
|
||||
@@ -136,7 +148,11 @@
|
||||
</div>
|
||||
<div class="tips">
|
||||
<p>GitHub链接带不带协议头均可,支持release、archive以及文件,转换后链接均可使用</a>。</p>
|
||||
<p id="sizeLimitDisplay">文件大小限制: ...</p>
|
||||
<div class="status-container">
|
||||
<p id="sizeLimitDisplay">文件大小限制: ...</p>
|
||||
<p id="whiteListStatus">白名单状态: ...</p>
|
||||
<p id="blackListStatus">黑名单状态: ...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -173,19 +189,57 @@
|
||||
alert('链接已复制到剪贴板');
|
||||
});
|
||||
|
||||
function fetchAPI() {
|
||||
fetch(window.location.origin + '/api')
|
||||
function fetchSizeLimit() {
|
||||
fetch(window.location.origin + '/api/size_limit')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const sizeLimitDisplay = document.getElementById('sizeLimitDisplay');
|
||||
const sizeInMB = (data.MaxResponseBodySize / (1024 * 1024)).toFixed(0);
|
||||
sizeLimitDisplay.textContent = `文件大小限制: ${sizeInMB} MB`;
|
||||
sizeLimitDisplay.textContent = `文件大小限制: ${data.MaxResponseBodySize} MB`;
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error fetching API:', error);
|
||||
|
||||
});
|
||||
}
|
||||
function fetchWhiteList() {
|
||||
fetch(window.location.origin + '/api/whitelist/status')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const whiteListStatus = document.getElementById('whiteListStatus');
|
||||
if (data.Whitelist) {
|
||||
whiteListStatus.textContent = `白名单状态: 已开启`;
|
||||
} else if (!data.Whitelist) {
|
||||
whiteListStatus.textContent = `白名单状态: 已关闭`;
|
||||
} else {
|
||||
whiteListStatus.textContent = `白名单状态: 未知`;
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error fetching API:', error);
|
||||
});
|
||||
}
|
||||
function fetchBlackList() {
|
||||
fetch(window.location.origin + '/api/blacklist/status')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const blackListStatus = document.getElementById('blackListStatus');
|
||||
if (data.Blacklist) {
|
||||
blackListStatus.textContent = `黑名单状态: 已开启`;
|
||||
} else if (!data.Blacklist) {
|
||||
blackListStatus.textContent = `黑名单状态: 已关闭`;
|
||||
} else {
|
||||
blackListStatus.textContent = `黑名单状态: 未知`;
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error fetching API:', error);
|
||||
});
|
||||
}
|
||||
function fetchAPI() {
|
||||
fetchSizeLimit();
|
||||
fetchWhiteList();
|
||||
fetchBlackList();
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', fetchAPI);
|
||||
</script>
|
||||
</body>
|
||||
@@ -195,8 +249,7 @@
|
||||
Copyright © 2024 WJQSERVER-STUDIO
|
||||
</p>
|
||||
<p>
|
||||
GitHub仓库地址:<a
|
||||
href="https://github.com/WJQSERVER-STUDIO/ghproxy">https://github.com/WJQSERVER-STUDIO/ghproxy</a>
|
||||
GitHub仓库地址:<a href="https://github.com/WJQSERVER-STUDIO/ghproxy">https://github.com/WJQSERVER-STUDIO/ghproxy</a>
|
||||
</p>
|
||||
<div id="visitor-info" style="text-align: center; margin-top: 15px;">
|
||||
<p>您的IP地址: <span id="visitor-ip"></span></p>
|
||||
|
||||
131
proxy/proxy.go
131
proxy/proxy.go
@@ -17,7 +17,13 @@ import (
|
||||
"github.com/imroc/req/v3"
|
||||
)
|
||||
|
||||
var logw = logger.Logw
|
||||
// 日志模块
|
||||
var (
|
||||
logw = logger.Logw
|
||||
logInfo = logger.LogInfo
|
||||
LogWarning = logger.LogWarning
|
||||
logError = logger.LogError
|
||||
)
|
||||
|
||||
var exps = []*regexp.Regexp{
|
||||
regexp.MustCompile(`^(?:https?://)?github\.com/([^/]+)/([^/]+)/(?:releases|archive)/.*`),
|
||||
@@ -34,7 +40,7 @@ func NoRouteHandler(cfg *config.Config) gin.HandlerFunc {
|
||||
matches := re.FindStringSubmatch(rawPath)
|
||||
|
||||
if len(matches) < 3 {
|
||||
logw("Invalid URL: %s", rawPath)
|
||||
LogWarning("Invalid URL: %s", rawPath)
|
||||
c.String(http.StatusForbidden, "Invalid URL.")
|
||||
return
|
||||
}
|
||||
@@ -45,14 +51,14 @@ func NoRouteHandler(cfg *config.Config) gin.HandlerFunc {
|
||||
pathmatches := regexp.MustCompile(`^([^/]+)/([^/]+)/([^/]+)/.*`)
|
||||
pathParts := pathmatches.FindStringSubmatch(matches[2])
|
||||
if len(pathParts) < 4 {
|
||||
logw("Invalid path: %s", rawPath)
|
||||
LogWarning("Invalid path: %s", rawPath)
|
||||
c.String(http.StatusForbidden, "Invalid path; expected username/repo.")
|
||||
return
|
||||
}
|
||||
|
||||
username := pathParts[2]
|
||||
repo := pathParts[3]
|
||||
logw("Blacklist Check > Username: %s, Repo: %s", username, repo)
|
||||
LogWarning("Blacklist Check > Username: %s, Repo: %s", username, repo)
|
||||
fullrepo := fmt.Sprintf("%s/%s", username, repo)
|
||||
|
||||
// 白名单检查
|
||||
@@ -61,7 +67,7 @@ func NoRouteHandler(cfg *config.Config) gin.HandlerFunc {
|
||||
if !whitelistpass {
|
||||
errMsg := fmt.Sprintf("Whitelist Blocked repo: %s", fullrepo)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": errMsg})
|
||||
logw(errMsg)
|
||||
LogWarning(errMsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -72,7 +78,7 @@ func NoRouteHandler(cfg *config.Config) gin.HandlerFunc {
|
||||
if blacklistpass {
|
||||
errMsg := fmt.Sprintf("Blacklist Blocked repo: %s", fullrepo)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": errMsg})
|
||||
logw(errMsg)
|
||||
LogWarning(errMsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -89,18 +95,18 @@ func NoRouteHandler(cfg *config.Config) gin.HandlerFunc {
|
||||
|
||||
if !auth.AuthHandler(c, cfg) {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
|
||||
logw("Unauthorized request: %s", rawPath)
|
||||
LogWarning("Unauthorized request: %s", rawPath)
|
||||
return
|
||||
}
|
||||
|
||||
logw("Matches: %v", matches)
|
||||
logInfo("Matches: %v", matches)
|
||||
|
||||
switch {
|
||||
case exps[0].MatchString(rawPath), exps[1].MatchString(rawPath), exps[3].MatchString(rawPath), exps[4].MatchString(rawPath):
|
||||
logw("%s Matched - USE proxy-chrome", rawPath)
|
||||
logInfo("%s Matched - USE proxy-chrome", rawPath)
|
||||
ProxyRequest(c, rawPath, cfg, "chrome")
|
||||
case exps[2].MatchString(rawPath):
|
||||
logw("%s Matched - USE proxy-git", rawPath)
|
||||
logInfo("%s Matched - USE proxy-git", rawPath)
|
||||
ProxyRequest(c, rawPath, cfg, "git")
|
||||
default:
|
||||
c.String(http.StatusForbidden, "Invalid input.")
|
||||
@@ -111,33 +117,18 @@ func NoRouteHandler(cfg *config.Config) gin.HandlerFunc {
|
||||
|
||||
func ProxyRequest(c *gin.Context, u string, cfg *config.Config, mode string) {
|
||||
method := c.Request.Method
|
||||
logw("%s %s", method, u)
|
||||
logInfo("%s %s", method, u)
|
||||
|
||||
client := req.C()
|
||||
client := createHTTPClient(mode)
|
||||
|
||||
switch mode {
|
||||
case "chrome":
|
||||
client.SetUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36").
|
||||
SetTLSFingerprintChrome().
|
||||
ImpersonateChrome()
|
||||
case "git":
|
||||
client.SetUserAgent("git/2.33.1")
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
body, err := readRequestBody(c)
|
||||
if err != nil {
|
||||
HandleError(c, fmt.Sprintf("Failed to read request body: %v", err))
|
||||
HandleError(c, err.Error())
|
||||
return
|
||||
}
|
||||
defer c.Request.Body.Close()
|
||||
|
||||
req := client.R().SetBody(body)
|
||||
|
||||
for key, values := range c.Request.Header {
|
||||
for _, value := range values {
|
||||
req.SetHeader(key, value)
|
||||
}
|
||||
}
|
||||
setRequestHeaders(c, req)
|
||||
|
||||
resp, err := SendRequest(req, method, u)
|
||||
if err != nil {
|
||||
@@ -147,17 +138,56 @@ func ProxyRequest(c *gin.Context, u string, cfg *config.Config, mode string) {
|
||||
defer resp.Body.Close()
|
||||
|
||||
if err := HandleResponseSize(resp, cfg, c); err != nil {
|
||||
logw("Error handling response size: %v", err)
|
||||
LogWarning("Error handling response size: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
CopyResponseHeaders(resp, c, cfg)
|
||||
c.Status(resp.StatusCode)
|
||||
if _, err := io.Copy(c.Writer, resp.Body); err != nil {
|
||||
logw("Failed to copy response body: %v", err)
|
||||
if err := copyResponseBody(c, resp.Body); err != nil {
|
||||
logError("Failed to copy response body: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// createHTTPClient 创建并配置 HTTP 客户端
|
||||
func createHTTPClient(mode string) *req.Client {
|
||||
client := req.C()
|
||||
switch mode {
|
||||
case "chrome":
|
||||
client.SetUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36").
|
||||
SetTLSFingerprintChrome().
|
||||
ImpersonateChrome()
|
||||
case "git":
|
||||
client.SetUserAgent("git/2.33.1")
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
// readRequestBody 读取请求体
|
||||
func readRequestBody(c *gin.Context) ([]byte, error) {
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read request body: %v", err)
|
||||
}
|
||||
defer c.Request.Body.Close()
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// setRequestHeaders 设置请求头
|
||||
func setRequestHeaders(c *gin.Context, req *req.Request) {
|
||||
for key, values := range c.Request.Header {
|
||||
for _, value := range values {
|
||||
req.SetHeader(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// copyResponseBody 复制响应体到客户端
|
||||
func copyResponseBody(c *gin.Context, respBody io.Reader) error {
|
||||
_, err := io.Copy(c.Writer, respBody)
|
||||
return err
|
||||
}
|
||||
|
||||
func SendRequest(req *req.Request, method, url string) (*req.Response, error) {
|
||||
switch method {
|
||||
case "GET":
|
||||
@@ -169,7 +199,7 @@ func SendRequest(req *req.Request, method, url string) (*req.Response, error) {
|
||||
case "DELETE":
|
||||
return req.Delete(url)
|
||||
default:
|
||||
logw("Unsupported method: %s", method)
|
||||
logInfo("Unsupported method: %s", method)
|
||||
return nil, fmt.Errorf("unsupported method: %s", method)
|
||||
}
|
||||
}
|
||||
@@ -181,14 +211,25 @@ func HandleResponseSize(resp *req.Response, cfg *config.Config, c *gin.Context)
|
||||
if err == nil && size > cfg.Server.SizeLimit {
|
||||
finalURL := resp.Request.URL.String()
|
||||
c.Redirect(http.StatusMovedPermanently, finalURL)
|
||||
logw("Redirecting to %s due to size limit (%d bytes)", finalURL, size)
|
||||
return fmt.Errorf("response size exceeds limit")
|
||||
LogWarning("Size limit exceeded: %s, Size: %d", finalURL, size)
|
||||
return fmt.Errorf("size limit exceeded: %d", size)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CopyResponseHeaders(resp *req.Response, c *gin.Context, cfg *config.Config) {
|
||||
removeHeaders(resp)
|
||||
|
||||
copyHeaders(resp, c)
|
||||
|
||||
setCORSHeaders(c, cfg)
|
||||
|
||||
setDefaultHeaders(c)
|
||||
}
|
||||
|
||||
// removeHeaders 移除指定的响应头
|
||||
func removeHeaders(resp *req.Response) {
|
||||
headersToRemove := map[string]struct{}{
|
||||
"Content-Security-Policy": {},
|
||||
"Referrer-Policy": {},
|
||||
@@ -198,35 +239,45 @@ func CopyResponseHeaders(resp *req.Response, c *gin.Context, cfg *config.Config)
|
||||
for header := range headersToRemove {
|
||||
resp.Header.Del(header)
|
||||
}
|
||||
}
|
||||
|
||||
// copyHeaders 复制响应头到 Gin 上下文
|
||||
func copyHeaders(resp *req.Response, c *gin.Context) {
|
||||
for key, values := range resp.Header {
|
||||
for _, value := range values {
|
||||
c.Header(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.Header("Access-Control-Allow-Origin", "")
|
||||
// setCORSHeaders 设置 CORS 相关的响应头
|
||||
func setCORSHeaders(c *gin.Context, cfg *config.Config) {
|
||||
if cfg.CORS.Enabled {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
} else {
|
||||
c.Header("Access-Control-Allow-Origin", "")
|
||||
}
|
||||
}
|
||||
|
||||
// setDefaultHeaders 设置默认的响应头
|
||||
func setDefaultHeaders(c *gin.Context) {
|
||||
c.Header("Age", "10")
|
||||
c.Header("Cache-Control", "max-age=300")
|
||||
}
|
||||
|
||||
func HandleError(c *gin.Context, message string) {
|
||||
c.String(http.StatusInternalServerError, fmt.Sprintf("server error %v", message))
|
||||
logw(message)
|
||||
LogWarning(message)
|
||||
}
|
||||
|
||||
func CheckURL(u string) []string {
|
||||
for _, exp := range exps {
|
||||
if matches := exp.FindStringSubmatch(u); matches != nil {
|
||||
logw("URL matched: %s, Matches: %v", u, matches[1:])
|
||||
logInfo("URL matched: %s, Matches: %v", u, matches[1:])
|
||||
return matches[1:]
|
||||
}
|
||||
}
|
||||
errMsg := fmt.Sprintf("Invalid URL: %s", u)
|
||||
logw(errMsg)
|
||||
LogWarning(errMsg)
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user