refactor: refactoring http request creation and sending (#395)

* refactoring http request creation and sending

* fix lint error

* increase the test coverage of client.go

* refactor: Change the style of HTTPRequestBuilder.Build func to one-argument-per-line.
This commit is contained in:
渡邉祐一 / Yuichi Watanabe
2023-06-22 18:57:52 +09:00
committed by GitHub
parent 157de0680f
commit f1b66967a4
20 changed files with 215 additions and 132 deletions

View File

@@ -57,21 +57,19 @@ func (c *Client) CreateFile(ctx context.Context, request FileRequest) (file File
return
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.fullURL("/files"), &b)
req, err := c.newRequest(ctx, http.MethodPost, c.fullURL("/files"),
withBody(&b), withContentType(builder.FormDataContentType()))
if err != nil {
return
}
req.Header.Set("Content-Type", builder.FormDataContentType())
err = c.sendRequest(req, &file)
return
}
// DeleteFile deletes an existing file.
func (c *Client) DeleteFile(ctx context.Context, fileID string) (err error) {
req, err := c.requestBuilder.Build(ctx, http.MethodDelete, c.fullURL("/files/"+fileID), nil)
req, err := c.newRequest(ctx, http.MethodDelete, c.fullURL("/files/"+fileID))
if err != nil {
return
}
@@ -83,7 +81,7 @@ func (c *Client) DeleteFile(ctx context.Context, fileID string) (err error) {
// ListFiles Lists the currently available files,
// and provides basic information about each file such as the file name and purpose.
func (c *Client) ListFiles(ctx context.Context) (files FilesList, err error) {
req, err := c.requestBuilder.Build(ctx, http.MethodGet, c.fullURL("/files"), nil)
req, err := c.newRequest(ctx, http.MethodGet, c.fullURL("/files"))
if err != nil {
return
}
@@ -96,7 +94,7 @@ func (c *Client) ListFiles(ctx context.Context) (files FilesList, err error) {
// such as the file name and purpose.
func (c *Client) GetFile(ctx context.Context, fileID string) (file File, err error) {
urlSuffix := fmt.Sprintf("/files/%s", fileID)
req, err := c.requestBuilder.Build(ctx, http.MethodGet, c.fullURL(urlSuffix), nil)
req, err := c.newRequest(ctx, http.MethodGet, c.fullURL(urlSuffix))
if err != nil {
return
}
@@ -107,23 +105,11 @@ func (c *Client) GetFile(ctx context.Context, fileID string) (file File, err err
func (c *Client) GetFileContent(ctx context.Context, fileID string) (content io.ReadCloser, err error) {
urlSuffix := fmt.Sprintf("/files/%s/content", fileID)
req, err := c.requestBuilder.Build(ctx, http.MethodGet, c.fullURL(urlSuffix), nil)
req, err := c.newRequest(ctx, http.MethodGet, c.fullURL(urlSuffix))
if err != nil {
return
}
c.setCommonHeaders(req)
res, err := c.config.HTTPClient.Do(req)
if err != nil {
return
}
if isFailureStatusCode(res) {
err = c.handleErrorResp(res)
return
}
content = res.Body
content, err = c.sendRequestRaw(req)
return
}