types
This commit is contained in:
@@ -42,9 +42,11 @@ type Response struct {
|
||||
}
|
||||
|
||||
func Fetch(ctx context.Context, args FetchArgs) (Response, error) {
|
||||
// Set Default Method and Headers
|
||||
method := "GET"
|
||||
headers := make(map[string]string)
|
||||
|
||||
// Apply Init Options
|
||||
if args.Init != nil {
|
||||
if args.Init.Method != "" {
|
||||
method = args.Init.Method
|
||||
@@ -54,15 +56,18 @@ func Fetch(ctx context.Context, args FetchArgs) (Response, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Create Request
|
||||
req, err := http.NewRequestWithContext(ctx, method, args.Input, nil)
|
||||
if err != nil {
|
||||
return Response{}, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
// Set Request Headers
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
// Execute Request
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return Response{}, fmt.Errorf("failed to fetch: %w", err)
|
||||
@@ -71,11 +76,13 @@ func Fetch(ctx context.Context, args FetchArgs) (Response, error) {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
// Read Response Body
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return Response{}, fmt.Errorf("failed to read body: %w", err)
|
||||
}
|
||||
|
||||
// Collect Response Headers
|
||||
resultHeaders := make(map[string]string)
|
||||
for key, values := range resp.Header {
|
||||
if len(values) > 0 {
|
||||
@@ -85,6 +92,7 @@ func Fetch(ctx context.Context, args FetchArgs) (Response, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Return Response
|
||||
return Response{
|
||||
OK: resp.StatusCode >= 200 && resp.StatusCode < 300,
|
||||
Status: resp.StatusCode,
|
||||
|
||||
Reference in New Issue
Block a user