go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/nodes/pkg/funcs/fetch_utils.go (about) 1 /* 2 3 Copyright (c) 2024 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package funcs 9 10 import ( 11 "bytes" 12 "context" 13 "fmt" 14 "io" 15 "net/http" 16 ) 17 18 func fetchURL(ctx context.Context, url string) (io.ReadCloser, error) { 19 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) 20 if err != nil { 21 return nil, fmt.Errorf("fetchURL new request failure; %w", err) 22 } 23 res, err := http.DefaultClient.Do(req) 24 if err != nil { 25 return nil, fmt.Errorf("fetchURL response failure; %w", err) 26 } 27 return res.Body, nil 28 } 29 30 func fetchURLMethod(ctx context.Context, url, method, body string) (io.ReadCloser, error) { 31 if method == "" { 32 method = http.MethodGet 33 } 34 var bodyReader io.Reader 35 if body != "" { 36 bodyReader = bytes.NewBufferString(body) 37 } 38 req, err := http.NewRequestWithContext(ctx, method, url, bodyReader) 39 if err != nil { 40 return nil, fmt.Errorf("fetchURL new request failure; %w", err) 41 } 42 res, err := http.DefaultClient.Do(req) 43 if err != nil { 44 return nil, fmt.Errorf("fetchURL response failure; %w", err) 45 } 46 return res.Body, nil 47 }