Compare commits

...

25 Commits
1.0.0 ... 1.1.1

Author SHA1 Message Date
WJQSERVER
c4ecf74d71 Merge branch 'main' of https://github.com/WJQSERVER-STUDIO/ghproxy 2024-10-02 21:44:36 +08:00
WJQSERVER
9f801bbac8 v1.1.1 2024-10-02 21:44:33 +08:00
WJQSERVER
a1fd8e59f0 Update README.md 2024-10-02 21:35:37 +08:00
WJQSERVER
df05c6a275 24w07a 2024-10-02 21:25:28 +08:00
WJQSERVER
8ae6a9e090 Bump Go to v1.23.2 2024-10-02 21:17:00 +08:00
里見 灯花
00283fa4d2 Update README.md 2024-09-29 08:46:32 +08:00
里見 灯花
b68593cbd0 Update README.md 2024-09-28 14:06:26 +08:00
WJQSERVER
c11fd11647 Update README.md 2024-09-27 16:54:47 +08:00
WJQSERVER
058610536b v1.1.0 2024-09-27 16:40:17 +08:00
WJQSERVER
7f321bd5f4 v1.1.0 2024-09-27 15:54:03 +08:00
WJQSERVER
3665bc9cfd 24w06b 2024-09-27 15:45:43 +08:00
WJQSERVER
fea70c01d8 24w06b 2024-09-27 15:27:53 +08:00
WJQSERVER
8412231b72 24w06b 2024-09-27 15:19:57 +08:00
WJQSERVER
178d5f14c2 24w06b 2024-09-27 15:18:47 +08:00
WJQSERVER
bb4e2d8ae7 24w06b 2024-09-27 15:09:55 +08:00
WJQSERVER
7d6d9d0da5 24w06b 2024-09-27 15:05:49 +08:00
WJQSERVER
a8d524739b 24w06b 2024-09-27 14:59:02 +08:00
WJQSERVER
93c3175206 24w06b 2024-09-27 14:56:17 +08:00
WJQSERVER
58b9fcd1c9 24w06b 2024-09-27 14:46:50 +08:00
WJQSERVER
af0c364662 24w06b 2024-09-27 14:30:37 +08:00
WJQSERVER
45246e124e 24w06b 2024-09-27 14:15:41 +08:00
WJQSERVER
0899397d2e 24w06b 2024-09-27 14:02:21 +08:00
WJQSERVER
efeb940676 fix 2024-09-26 17:44:33 +08:00
WJQSERVER
19e2909699 fix 2024-09-25 14:14:09 +08:00
WJQSERVER
48c2ea8f97 Create dependabot.yml 2024-09-25 14:10:47 +08:00
16 changed files with 359 additions and 224 deletions

11
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "gomod" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"

View File

@@ -14,7 +14,7 @@ jobs:
env:
OUTPUT_BINARY: ghproxy
OUTPUT_ARCHIVE: ghproxy.tar.gz
GO_VERSION: 1.23.1
GO_VERSION: 1.23.2
steps:
- uses: actions/checkout@v3

View File

@@ -14,7 +14,7 @@ jobs:
env:
OUTPUT_BINARY: ghproxy
OUTPUT_ARCHIVE: ghproxy.tar.gz
GO_VERSION: 1.23.1
GO_VERSION: 1.23.2
steps:
- uses: actions/checkout@v3

View File

@@ -1,5 +1,40 @@
# 更新日志
v1.1.1
---
- CHANGE: 修改部分代码与golang-temp项目定义的开发规范保持一致
- CHANGE: 更新Go版本至v1.23.2
- CHANGE: 跟随Caddy更新,修改Caddyfile配置
24w07b
---
- CHANGE: 修改部分代码与golang-temp项目定义的开发规范保持一致
- CHANGE: 更新Go版本至v1.23.2
- CHANGE: 跟随Caddy更新,修改Caddyfile配置
24w07a
---
- CHANGE: 修改部分代码与golang-temp项目定义的开发规范保持一致
- CHANGE: 更新Go版本至v1.23.2
v1.1.0
---
- CHANGE: 优化代码结构,对main函数进行模块化,提升可读性
- CHANGE: Docker代理功能移至DEV版本内,保证稳定性
- ADD&CHANGE: 增加Auth(用户鉴权)模块,并改进其的错误处理与日志记录
- CHANGE: 日志模块引入goroutine协程,提升性能
- ADD: 将主要实现分离,作为Proxy模块,并优化代码结构
- ADD: 新增安全政策
24w06b
---
- CHANGE: 优化代码结构,对main函数进行模块化,提升可读性
- CHANGE: Docker代理功能移至DEV版本内,保证稳定性
- ADD&CHANGE: 增加Auth(用户鉴权)模块,并改进其的错误处理与日志记录
- CHANGE: 日志模块引入goroutine协程,提升性能 (实验性功能)
- ADD: 将主要实现分离,作为Proxy模块,并优化代码结构
- ADD: 新增安全政策
v1.0.0
---
- CHANGE: 项目正式发布, 并迁移至[WJQSERVER-STUDIO/ghproxy](https://github.com/WJQSERVER-STUDIO/ghproxy)

View File

@@ -1 +1 @@
24w06a
24w07b

View File

@@ -5,6 +5,8 @@
使用Go实现的GHProxy,用于加速部分地区Github仓库的拉取,支持速率限制,用户鉴权,支持Docker部署
[DEMO](ghproxy.1888866.xyz)
## 项目说明
### 项目特点
@@ -14,6 +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)模板构建,具有标准化的日志记录与构建流程
@@ -63,7 +66,7 @@ docker run -p 7210:80 -v ./ghproxy/log/run:/data/ghproxy/log -v ./ghproxy/log/ca
port: 8080 # 监听端口
host: "127.0.0.1" # 监听地址
sizelimit: 131072000 # 125MB
logfilepath: "/data/ghproxy/log/ghproxy-0rtt.log" # 日志文件路径
logfilepath: "/data/ghproxy/log/ghproxy.log" # 日志文件路径
CorsAllowOrigins: true # 是否允许跨域请求
auth: true # 是否开启鉴权
authtoken: "test" # 鉴权token
@@ -84,7 +87,7 @@ example.com {
}
```
## TODO & BETA
## TODO & DEV
### TODO
@@ -92,6 +95,6 @@ example.com {
- [x] 改进程序效率
- [x] 用户鉴权
### BETA
### DEV
- [x] Docker Pull 代理

35
SECURITY.MD Normal file
View File

@@ -0,0 +1,35 @@
# 安全政策
## 支持的版本
以下版本的项目目前正在接受安全更新:
| 版本 | 是否支持 |
| --- | --- |
| v1.x.x | :white_check_mark: |
| **w**a/b | :warning: 这是测试版本,用于开发测试,可能存在未知的安全隐患 |
| v0.x.x | :x: 这些版本不再受支持 |
### 版本说明
- **v1.0.0**: 这是正式发布的版本
- **xx W xx A/B***: 这是开发测试版本,可能存在未知的安全隐患。不推荐在生产环境中使用。
- **v0.x.x**: 这些早期版本不再受支持,建议尽快升级到 v1.0.0 或更高版本。
### 用户须知
本项目为开源项目,开发者不对使用本项目造成的任何损失或问题承担责任。用户需自行评估并承担使用本项目的风险。
使用本项目,请遵循 **[WSL (WJQSERVER-STUDIO LICENSE)](https://wjqserver-studio.github.io/LICENSE/LICENSE.html)** 协议。
## 报告漏洞
如果您发现本项目存在安全漏洞,请通过发送ISSUES或尝试联系项目维护者来报告。请在您的报告中包含以下信息:
1. 漏洞的描述,包括重现步骤。
2. 受到漏洞影响的项目版本。
3. 任何缓解因素,如利用难度或漏洞影响。
项目维护者将审查您的报告,并尽快解决该漏洞。请注意,根据漏洞的复杂程度,可能需要一些时间来调查和修复问题。
感谢您帮助保护本项目的安全!

View File

@@ -1 +1 @@
1.0.0
1.1.1

35
auth/auth.go Normal file
View File

@@ -0,0 +1,35 @@
package auth
import (
"ghproxy/config"
"ghproxy/logger"
"github.com/gin-gonic/gin"
)
var logw = logger.Logw
func AuthHandler(c *gin.Context, cfg *config.Config) bool {
// 如果身份验证未启用,直接返回 true
if !cfg.Auth {
logw("auth PASSED")
return true
}
// 获取 auth_token 参数
authToken := c.Query("auth_token")
logw("auth_token received: %s", authToken)
// 验证 token
if authToken == "" {
logw("auth FAILED: no auth_token provided")
return false
}
isValid := authToken == cfg.AuthToken
if !isValid {
logw("auth FAILED: invalid auth_token: %s", authToken)
}
return isValid
}

View File

@@ -4,7 +4,7 @@
https_port 443
order cache before rewrite
cache {
cache_name W-Cache
cache_name GhProxyCache
}
log {
level INFO
@@ -20,7 +20,7 @@
format transform `{request>headers>X-Forwarded-For>[0]:request>remote_ip} - {user_id} [{ts}] "{request>method} {request>uri} {request>proto}" {status} {size} "{request>headers>Referer>[0]}" "{request>headers>User-Agent>[0]}"` {
time_format "02/Jan/2006:15:04:05 -0700"
}
output file /data/caddy/log/{args.0}/access.log {
output file /data/caddy/log/{args[0]}/access.log {
roll_size 5MB
roll_keep 10
roll_keep_for 24h
@@ -48,8 +48,8 @@
(cache) {
cache {
allowed_http_verbs GET
stale {args.0}
ttl {args.1}
stale {args[0]}
ttl {args[1]}
}
}
@@ -68,7 +68,7 @@
(rate_limit) {
route /* {
rate_limit {remote.ip} {args.0}r/m 10000 429
rate_limit {remote.ip} {args[0]}r/m 10000 429
}
}
@@ -77,7 +77,7 @@
to 127.0.0.1:8080
import header_realip
}
import log go
import log ghproxy
import cache 0s 600s
import error_page
import encode

View File

@@ -4,7 +4,7 @@
https_port 443
order cache before rewrite
cache {
cache_name W-Cache
cache_name GhProxyCache
}
log {
level INFO
@@ -20,7 +20,7 @@
format transform `{request>headers>X-Forwarded-For>[0]:request>remote_ip} - {user_id} [{ts}] "{request>method} {request>uri} {request>proto}" {status} {size} "{request>headers>Referer>[0]}" "{request>headers>User-Agent>[0]}"` {
time_format "02/Jan/2006:15:04:05 -0700"
}
output file /data/caddy/log/{args.0}/access.log {
output file /data/caddy/log/{args[0]}/access.log {
roll_size 5MB
roll_keep 10
roll_keep_for 24h
@@ -48,8 +48,8 @@
(cache) {
cache {
allowed_http_verbs GET
stale {args.0}
ttl {args.1}
stale {args[0]}
ttl {args[1]}
}
}
@@ -68,7 +68,7 @@
(rate_limit) {
route /* {
rate_limit {remote.ip} {args.0}r/m 10000 429
rate_limit {remote.ip} {args[0]}r/m 10000 429
}
}
@@ -77,7 +77,7 @@
to 127.0.0.1:8080
import header_realip
}
import log go
import log ghproxy
import cache 0s 600s
import error_page
import encode
@@ -94,23 +94,6 @@
file_server
import cache 60s 24h
}
handle_errors {
@redirects `{err.status_code} in [301, 302, 307]`
reverse_proxy @redirects {
header_up Location {http.response.header.Location}
}
}
route /v2* {
reverse_proxy https://registry-1.docker.io {
header_up Host registry-1.docker.io
header_up X-Real-IP {remote}
header_up X-Forwarded-For {http.request.header.X-Forwarded-For}
header_up X-Forwarded-Proto {scheme}
header_up Authorization {http.request.header.Authorization}
}
}
}
import /data/caddy/config.d/*

View File

@@ -1,7 +1,7 @@
port: 8080
host: "127.0.0.1"
sizelimit: 131072000 # 125MB
logfilepath: "/data/ghproxy/log/ghproxy-0rtt.log"
logfilepath: "/data/ghproxy/log/ghproxy.log"
CorsAllowOrigins: true
auth: true
authtoken: "test"
auth: false
authtoken: "test"

2
go.mod
View File

@@ -1,6 +1,6 @@
module ghproxy
go 1.23.1
go 1.23.2
require (
github.com/andybalholm/brotli v1.1.0 // indirect

View File

@@ -8,8 +8,12 @@ import (
"time"
)
var logFile *os.File
var logger *log.Logger
var (
logFile *os.File
logger *log.Logger
logChannel = make(chan string, 100) // 创建一个缓冲通道
quitChannel = make(chan struct{}) // 用于通知退出
)
// Init 初始化日志记录器,接受日志文件路径作为参数
func Init(logFilePath string) error {
@@ -19,17 +23,29 @@ func Init(logFilePath string) error {
return err
}
logger = log.New(logFile, "", 0) // 不使用默认前缀
go logWorker() // 启动 goroutine 处理日志
return nil
}
// Log 直接记录日志的函数,带有时间戳
func Log(customMessage string) {
if logger != nil {
timestamp := time.Now().Format("02/Jan/2006:15:04:05 -0700") // 使用自定义时间格式
logger.Println(timestamp + " - " + customMessage)
// logWorker 处理日志记录
func logWorker() {
for {
select {
case msg := <-logChannel:
timestamp := time.Now().Format("02/Jan/2006:15:04:05 -0700")
logger.Println(timestamp + " - " + msg) // 写入日志
case <-quitChannel:
return // 退出 goroutine
}
}
}
// Log 直接记录日志的函数
func Log(customMessage string) {
logChannel <- customMessage // 将日志消息发送到通道
}
// Logw 用于格式化日志记录
func Logw(format string, args ...interface{}) {
message := fmt.Sprintf(format, args...) // 格式化消息
@@ -39,6 +55,9 @@ func Logw(format string, args ...interface{}) {
// Close 关闭日志文件
func Close() {
if logFile != nil {
logFile.Close()
quitChannel <- struct{}{} // 通知日志 goroutine 退出
if err := logFile.Close(); err != nil {
Log("Error closing log file: " + err.Error()) // 记录关闭日志时的错误
}
}
}

182
main.go
View File

@@ -3,23 +3,21 @@ package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"regexp"
"strconv"
"strings"
"ghproxy/config"
"ghproxy/logger"
"ghproxy/proxy"
"github.com/gin-gonic/gin"
"github.com/imroc/req/v3"
)
var cfg *config.Config
var logw = logger.Logw
var router *gin.Engine
var configfile = "/data/ghproxy/config/config.yaml"
var (
exps = []*regexp.Regexp{
@@ -34,7 +32,7 @@ var (
func loadConfig() {
var err error
// 初始化配置
cfg, err = config.LoadConfig("/data/ghproxy/config/config.yaml")
cfg, err = config.LoadConfig(configfile)
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
@@ -75,7 +73,9 @@ func init() {
})
// 未匹配路由处理
router.NoRoute(noRouteHandler(cfg))
router.NoRoute(func(c *gin.Context) {
proxy.NoRouteHandler(cfg)(c)
})
}
func main() {
@@ -95,173 +95,3 @@ func api(c *gin.Context) {
"MaxResponseBodySize": cfg.SizeLimit,
})
}
func authHandler(c *gin.Context) bool {
if cfg.Auth {
authToken := c.Query("auth_token")
return authToken == cfg.AuthToken
}
return true
}
func noRouteHandler(config *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
rawPath := strings.TrimPrefix(c.Request.URL.RequestURI(), "/")
re := regexp.MustCompile(`^(http:|https:)?/?/?(.*)`)
matches := re.FindStringSubmatch(rawPath)
rawPath = "https://" + matches[2]
matches = checkURL(rawPath)
if matches == nil {
c.String(http.StatusForbidden, "Invalid input.")
return
}
if exps[1].MatchString(rawPath) {
rawPath = strings.Replace(rawPath, "/blob/", "/raw/", 1)
}
if !authHandler(c) {
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
logw("Unauthorized request: %s", rawPath)
return
}
// 日志记录
logw("Request: %s %s", c.Request.Method, rawPath)
logw("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)
proxyRequest(c, rawPath, config, "chrome")
case exps[2].MatchString(rawPath):
logw("%s Matched - USE proxy-git", rawPath)
proxyRequest(c, rawPath, config, "git")
default:
c.String(http.StatusForbidden, "Invalid input.")
return
}
}
}
func proxyRequest(c *gin.Context, u string, config *config.Config, mode string) {
method := c.Request.Method
logw("%s Method: %s", u, method)
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")
}
// 读取请求体
body, err := io.ReadAll(c.Request.Body)
if err != nil {
handleError(c, fmt.Sprintf("Failed to read request body: %v", err))
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)
}
}
// 发送请求并处理响应
resp, err := sendRequest(req, method, u)
if err != nil {
handleError(c, fmt.Sprintf("Failed to send request: %v", err))
return
}
defer resp.Body.Close()
// 检查响应内容长度并处理重定向
if err := handleResponseSize(resp, config, c); err != nil {
logw("Error handling response size: %v", err)
return
}
copyResponseHeaders(resp, c, config)
c.Status(resp.StatusCode)
if _, err := io.Copy(c.Writer, resp.Body); err != nil {
logw("Failed to copy response body: %v", err)
}
}
func sendRequest(req *req.Request, method, url string) (*req.Response, error) {
switch method {
case "GET":
return req.Get(url)
case "POST":
return req.Post(url)
case "PUT":
return req.Put(url)
case "DELETE":
return req.Delete(url)
default:
return nil, fmt.Errorf("unsupported method: %s", method)
}
}
func handleResponseSize(resp *req.Response, config *config.Config, c *gin.Context) error {
contentLength := resp.Header.Get("Content-Length")
if contentLength != "" {
size, err := strconv.Atoi(contentLength)
if err == nil && size > config.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")
}
}
return nil
}
func copyResponseHeaders(resp *req.Response, c *gin.Context, config *config.Config) {
headersToRemove := []string{"Content-Security-Policy", "Referrer-Policy", "Strict-Transport-Security"}
for _, header := range headersToRemove {
resp.Header.Del(header)
}
for key, values := range resp.Header {
for _, value := range values {
c.Header(key, value)
}
}
if config.CORSOrigin {
c.Header("Access-Control-Allow-Origin", "*")
} else {
c.Header("Access-Control-Allow-Origin", "")
}
}
func handleError(c *gin.Context, message string) {
c.String(http.StatusInternalServerError, fmt.Sprintf("server error %v", message))
logw(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:])
return matches[1:]
}
}
logw("Invalid URL: %s", u)
return nil
}

184
proxy/proxy.go Normal file
View File

@@ -0,0 +1,184 @@
// proxy/proxy.go 实验性
package proxy
import (
"fmt"
"io"
"net/http"
"regexp"
"strconv"
"strings"
"ghproxy/auth"
"ghproxy/config"
"ghproxy/logger"
"github.com/gin-gonic/gin"
"github.com/imroc/req/v3"
)
var logw = logger.Logw
var cfg *config.Config
var exps = []*regexp.Regexp{
regexp.MustCompile(`^(?:https?://)?github\.com/([^/]+)/([^/]+)/(?:releases|archive)/.*`),
regexp.MustCompile(`^(?:https?://)?github\.com/([^/]+)/([^/]+)/(?:blob|raw)/.*`),
regexp.MustCompile(`^(?:https?://)?github\.com/([^/]+)/([^/]+)/(?:info|git-).*`),
regexp.MustCompile(`^(?:https?://)?raw\.github(?:usercontent|)\.com/([^/]+)/([^/]+)/.+?/.+`),
regexp.MustCompile(`^(?:https?://)?gist\.github\.com/([^/]+)/.+?/.+`),
}
func NoRouteHandler(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
rawPath := strings.TrimPrefix(c.Request.URL.RequestURI(), "/")
re := regexp.MustCompile(`^(http:|https:)?/?/?(.*)`)
matches := re.FindStringSubmatch(rawPath)
rawPath = "https://" + matches[2]
matches = CheckURL(rawPath)
if matches == nil {
c.String(http.StatusForbidden, "Invalid input.")
return
}
if exps[1].MatchString(rawPath) {
rawPath = strings.Replace(rawPath, "/blob/", "/raw/", 1)
}
if !auth.AuthHandler(c, cfg) {
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
logw("Unauthorized request: %s", rawPath)
return
}
logw("Request: %s %s", c.Request.Method, rawPath)
logw("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)
ProxyRequest(c, rawPath, cfg, "chrome")
case exps[2].MatchString(rawPath):
logw("%s Matched - USE proxy-git", rawPath)
ProxyRequest(c, rawPath, cfg, "git")
default:
c.String(http.StatusForbidden, "Invalid input.")
return
}
}
}
func ProxyRequest(c *gin.Context, u string, cfg *config.Config, mode string) {
method := c.Request.Method
logw("%s Method: %s", u, method)
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")
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
HandleError(c, fmt.Sprintf("Failed to read request body: %v", err))
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)
}
}
resp, err := SendRequest(req, method, u)
if err != nil {
HandleError(c, fmt.Sprintf("Failed to send request: %v", err))
return
}
defer resp.Body.Close()
if err := HandleResponseSize(resp, cfg, c); err != nil {
logw("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)
}
}
func SendRequest(req *req.Request, method, url string) (*req.Response, error) {
switch method {
case "GET":
return req.Get(url)
case "POST":
return req.Post(url)
case "PUT":
return req.Put(url)
case "DELETE":
return req.Delete(url)
default:
return nil, fmt.Errorf("unsupported method: %s", method)
}
}
func HandleResponseSize(resp *req.Response, cfg *config.Config, c *gin.Context) error {
contentLength := resp.Header.Get("Content-Length")
if contentLength != "" {
size, err := strconv.Atoi(contentLength)
if err == nil && size > cfg.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")
}
}
return nil
}
func CopyResponseHeaders(resp *req.Response, c *gin.Context, cfg *config.Config) {
headersToRemove := []string{"Content-Security-Policy", "Referrer-Policy", "Strict-Transport-Security"}
for _, header := range headersToRemove {
resp.Header.Del(header)
}
for key, values := range resp.Header {
for _, value := range values {
c.Header(key, value)
}
}
if cfg.CORSOrigin {
c.Header("Access-Control-Allow-Origin", "*")
} else {
c.Header("Access-Control-Allow-Origin", "")
}
}
func HandleError(c *gin.Context, message string) {
c.String(http.StatusInternalServerError, fmt.Sprintf("server error %v", message))
logw(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:])
return matches[1:]
}
}
logw("Invalid URL: %s", u)
return nil
}