Skip to content

Commit 40ce11f

Browse files
committed
perfect: 优化 newHTTPReq 请求构建逻辑
1 parent 13fda2d commit 40ce11f

2 files changed

Lines changed: 14 additions & 9 deletions

File tree

internal/service/alist/alist.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ func doRequest[T any](client *Client, r Request) (*T, error) {
145145
}
146146
}
147147

148-
req := newHTTPReq(client.GetBaseURLString(), r)
148+
req := newHTTPReq(r, client.baseURL)
149149
req.Header.Set("Accept", "application/json")
150150
req.Header.Set("Content-Type", "application/json")
151151
if r.NeedAuth() {
@@ -173,7 +173,7 @@ func doRequest[T any](client *Client, r Request) (*T, error) {
173173
}
174174

175175
if resp.Code != http.StatusOK {
176-
return nil, fmt.Errorf("请求失败HTTP 状态码: %d, 响应状态码: %d, 响应信息: %s", res.StatusCode, resp.Code, resp.Message)
176+
return nil, fmt.Errorf("请求失败, HTTP 状态码: %d, 响应状态码: %d, 响应信息: %s", res.StatusCode, resp.Code, resp.Message)
177177
}
178178

179179
if cacheKey != "" && client.cache != nil {

internal/service/alist/request.go

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"io"
88
"net/http"
9+
"net/url"
910
"strconv"
1011
)
1112

@@ -24,16 +25,20 @@ func getReqBody(r Request) io.Reader {
2425
return bytes.NewBuffer(b)
2526
}
2627

27-
func newHTTPReq(endpoint string, r Request) *http.Request {
28-
var (
29-
req *http.Request
30-
err error
31-
)
28+
func newHTTPReq(r Request, baseURL *url.URL) *http.Request {
29+
var body io.Reader
3230
if r.GetMethod() == http.MethodGet {
33-
req, err = http.NewRequest(r.GetMethod(), endpoint+r.GetAPIPath(), nil)
31+
body = nil
3432
} else {
35-
req, err = http.NewRequest(r.GetMethod(), endpoint+r.GetAPIPath(), getReqBody(r))
33+
body = getReqBody(r)
3634
}
35+
36+
req, err := http.NewRequest(
37+
r.GetMethod(),
38+
baseURL.JoinPath(r.GetAPIPath()).String(),
39+
body,
40+
)
41+
3742
if err != nil {
3843
panic(fmt.Errorf("创建请求失败: %w", err))
3944
}

0 commit comments

Comments
 (0)