fonchain-fiee/pkg/service/redirect/redirect.go
2025-05-22 20:19:42 +08:00

81 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package redirect
import (
"errors"
"fmt"
"fonchain-fiee/pkg/service"
"github.com/gin-gonic/gin"
"io"
"net/http"
"time"
)
// ToRedirectRealUrl 重定向到指定位置
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)
}
// ToRedirectRealUrlAdnRand 重定向到指定位置
func ToRedirectRealUrlAdnRand(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+fmt.Sprintf("?time=%d", time.Now().Unix()))
}
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)
}