fonchain-fiee/pkg/service/redirect/redirect.go

81 lines
1.8 KiB
Go
Raw Normal View History

2025-02-20 08:24:49 +00:00
package redirect
import (
"errors"
"fmt"
2025-02-20 12:55:54 +00:00
"fonchain-fiee/pkg/service"
2025-02-20 08:24:49 +00:00
"github.com/gin-gonic/gin"
2025-05-22 12:19:42 +00:00
"io"
2025-02-20 08:24:49 +00:00
"net/http"
"time"
)
2025-02-20 08:38:16 +00:00
// ToRedirectRealUrl 重定向到指定位置
2025-02-20 08:24:49 +00:00
func ToRedirectRealUrl(c *gin.Context) {
realUrl := c.Query("base_redirect_url")
if realUrl == "" {
service.Error(c, errors.New("not real url"))
return
}
c.Redirect(http.StatusMovedPermanently, realUrl)
}
2025-02-20 08:38:16 +00:00
// ToRedirectRealUrlAdnRand 重定向到指定位置
2025-02-20 08:24:49 +00:00
func ToRedirectRealUrlAdnRand(c *gin.Context) {
realUrl := c.Query("base_redirect_url")
if realUrl == "" {
service.Error(c, errors.New("not real url"))
return
}
2025-02-20 08:38:16 +00:00
c.Redirect(http.StatusMovedPermanently, realUrl+fmt.Sprintf("?time=%d", time.Now().Unix()))
2025-02-20 08:24:49 +00:00
}
2025-05-22 12:19:42 +00:00
func ForwardTest(c *gin.Context) {
// 1. 创建HTTP客户端设置超时避免长时间等待
client := &http.Client{
Timeout: 10 * time.Second,
}
// 2. 构造请求
req, err := http.NewRequest("GET", "https://stockanalysis.com/chart/__data.json", nil)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to create request",
})
return
}
// 3. 添加原始请求的查询参数(可选)
req.URL.RawQuery = c.Request.URL.RawQuery
// 4. 添加必要的请求头根据目标API要求
req.Header.Set("User-Agent", "Mozilla/5.0")
// 可以添加其他必要的headers如:
// req.Header.Set("Accept", "application/json")
// 5. 发送请求
resp, err := client.Do(req)
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{
"error": "Failed to fetch data from target API",
})
return
}
defer resp.Body.Close()
// 6. 读取响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to read response body",
})
return
}
// 7. 转发响应
c.Data(resp.StatusCode, resp.Header.Get("Content-Type"), body)
}