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:
committed by
GitHub
parent
157de0680f
commit
f1b66967a4
@@ -3,11 +3,12 @@ package openai
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type RequestBuilder interface {
|
||||
Build(ctx context.Context, method, url string, request any) (*http.Request, error)
|
||||
Build(ctx context.Context, method, url string, body any, header http.Header) (*http.Request, error)
|
||||
}
|
||||
|
||||
type HTTPRequestBuilder struct {
|
||||
@@ -20,21 +21,32 @@ func NewRequestBuilder() *HTTPRequestBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
func (b *HTTPRequestBuilder) Build(ctx context.Context, method, url string, request any) (*http.Request, error) {
|
||||
if request == nil {
|
||||
return http.NewRequestWithContext(ctx, method, url, nil)
|
||||
func (b *HTTPRequestBuilder) Build(
|
||||
ctx context.Context,
|
||||
method string,
|
||||
url string,
|
||||
body any,
|
||||
header http.Header,
|
||||
) (req *http.Request, err error) {
|
||||
var bodyReader io.Reader
|
||||
if body != nil {
|
||||
if v, ok := body.(io.Reader); ok {
|
||||
bodyReader = v
|
||||
} else {
|
||||
var reqBytes []byte
|
||||
reqBytes, err = b.marshaller.Marshal(body)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
bodyReader = bytes.NewBuffer(reqBytes)
|
||||
}
|
||||
}
|
||||
|
||||
var reqBytes []byte
|
||||
reqBytes, err := b.marshaller.Marshal(request)
|
||||
req, err = http.NewRequestWithContext(ctx, method, url, bodyReader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return
|
||||
}
|
||||
|
||||
return http.NewRequestWithContext(
|
||||
ctx,
|
||||
method,
|
||||
url,
|
||||
bytes.NewBuffer(reqBytes),
|
||||
)
|
||||
if header != nil {
|
||||
req.Header = header
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user