1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| package util
import ( "context" "io" "net/http"
"github.com/pkg/errors" )
var HTTPDefaultClient = http.DefaultClient
type HTTPRequest struct { *http.Request client *http.Client }
func NewHTTPRequest(ctx context.Context, method string, url string, bodies ...io.Reader) *HTTPRequest { if method == "" { method = http.MethodGet } var body io.Reader = http.NoBody if len(bodies) > 0 { body = bodies[0] } ret, _ := http.NewRequestWithContext(ctx, method, url, body) return &HTTPRequest{Request: ret} }
func NewHTTPGet(ctx context.Context, url string) *HTTPRequest { return NewHTTPRequest(ctx, http.MethodGet, url, http.NoBody) }
func NewHTTPPost(ctx context.Context, url string, body io.Reader) *HTTPRequest { return NewHTTPRequest(ctx, http.MethodPost, url, body) }
func (r *HTTPRequest) WithHeader(k string, v string) *HTTPRequest { r.Header.Set(k, v) return r }
func (r *HTTPRequest) WithClient(c *http.Client) *HTTPRequest { r.client = c return r }
func (r *HTTPRequest) Run() (*http.Response, error) { cl := Choose(r.client == nil, HTTPDefaultClient, r.client) rsp, err := cl.Do(r.Request) if err != nil { return nil, err } return rsp, nil }
func (r *HTTPRequest) RunSimple() (*http.Response, []byte, error) { rsp, err := r.Run() if err != nil { return nil, nil, err } defer func() { _ = rsp.Body.Close() }() b, _ := io.ReadAll(rsp.Body) if rsp.StatusCode != http.StatusOK { return rsp, b, errors.Errorf("response from url [%s] has status [%d], expected [200]", r.URL, rsp.StatusCode) } return rsp, b, nil }
|