36 lines
797 B
Go
36 lines
797 B
Go
package core
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// FetchURL 执行 HTTP GET 请求并返回响应状态码和响应体
|
|
func FetchURL(url string, timeout time.Duration) (int, string, error) {
|
|
// 创建自定义 HTTP 客户端
|
|
client := &http.Client{
|
|
Timeout: timeout,
|
|
}
|
|
// 创建请求
|
|
req, err := http.NewRequest("GET", url, nil)
|
|
if err != nil {
|
|
return 0, "", fmt.Errorf("failed to create request: %w", err)
|
|
}
|
|
|
|
// 发送请求
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return 0, "", fmt.Errorf("failed to make GET request: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
// 读取响应内容
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return resp.StatusCode, "", fmt.Errorf("failed to read response body: %w", err)
|
|
}
|
|
return resp.StatusCode, string(body), nil
|
|
}
|