48 lines
1.4 KiB
Go
48 lines
1.4 KiB
Go
|
|
package client
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"context"
|
|||
|
|
"fmt"
|
|||
|
|
"io"
|
|||
|
|
"net/http"
|
|||
|
|
|
|||
|
|
"schedule_converter/config"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// FetchHTML 发送 HTTP 请求并返回解码后的 HTML 字符串(处理 GBK 字符集)。
|
|||
|
|
// method 为 "GET" 或 "POST";path 拼接到 config.BaseURL 之后;body 为请求体(GET 传 nil)。
|
|||
|
|
// referer 为可选的 Referer 路径(拼接到 BaseURL 之后),不需要时传 ""。
|
|||
|
|
func FetchHTML(ctx context.Context, httpClient *http.Client, method, path string, body io.Reader, contentType, referer string) (string, error) {
|
|||
|
|
resp, err := doRequest(ctx, httpClient, method, path, body, contentType, referer)
|
|||
|
|
if err != nil {
|
|||
|
|
return "", err
|
|||
|
|
}
|
|||
|
|
defer resp.Body.Close()
|
|||
|
|
|
|||
|
|
if resp.StatusCode != http.StatusOK {
|
|||
|
|
return "", fmt.Errorf("请求 %s 失败, 状态码: %d", path, resp.StatusCode)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return DecodeResponseBody(resp)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// doRequest 构造并执行请求,设置 header(可选 Referer),透传 ctx。
|
|||
|
|
func doRequest(ctx context.Context, httpClient *http.Client, method, path string, body io.Reader, contentType, referer string) (*http.Response, error) {
|
|||
|
|
url := config.Get().BaseURL + path
|
|||
|
|
req, err := http.NewRequestWithContext(ctx, method, url, body)
|
|||
|
|
if err != nil {
|
|||
|
|
return nil, err
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if contentType != "" {
|
|||
|
|
req.Header = GetHeadersWithContentType(contentType)
|
|||
|
|
} else {
|
|||
|
|
req.Header = GetHeaders()
|
|||
|
|
}
|
|||
|
|
if referer != "" {
|
|||
|
|
req.Header.Set("Referer", config.Get().BaseURL+referer)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return httpClient.Do(req)
|
|||
|
|
}
|