github.com/richardwilkes/toolbox@v1.121.0/formats/json/http.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package json 11 12 import ( 13 "bytes" 14 "context" 15 "net/http" 16 17 "github.com/richardwilkes/toolbox/errs" 18 "github.com/richardwilkes/toolbox/xio" 19 ) 20 21 // GetRequest calls http.Get with the URL and returns the response body as a new Data object. 22 func GetRequest(url string) (statusCode int, body *Data, err error) { 23 return GetRequestWithContext(context.Background(), url) 24 } 25 26 // GetRequestWithContext calls http.Get with the URL and returns the response body as a new Data object. 27 func GetRequestWithContext(ctx context.Context, url string) (statusCode int, body *Data, err error) { 28 var req *http.Request 29 req, err = http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) 30 if err != nil { 31 return 0, nil, errs.NewWithCause("unable to create request", err) 32 } 33 return makeRequest(req) 34 } 35 36 // PostRequest calls http.Post with the URL and the contents of this Data object and returns the response body as a new 37 // Data object. 38 func (j *Data) PostRequest(url string) (statusCode int, body *Data, err error) { 39 return j.PostRequestWithContext(context.Background(), url) 40 } 41 42 // PostRequestWithContext calls http.Post with the URL and the contents of this Data object and returns the response 43 // body as a new Data object. 44 func (j *Data) PostRequestWithContext(ctx context.Context, url string) (statusCode int, body *Data, err error) { 45 var req *http.Request 46 req, err = http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(j.Bytes())) 47 if err != nil { 48 return 0, nil, errs.NewWithCause("unable to create request", err) 49 } 50 req.Header.Set("Content-Type", "application/json") 51 return makeRequest(req) 52 } 53 54 func makeRequest(req *http.Request) (statusCode int, body *Data, err error) { 55 var rsp *http.Response 56 if rsp, err = http.DefaultClient.Do(req); err != nil { 57 return 0, &Data{}, errs.NewWithCause("request failed", err) 58 } 59 defer xio.DiscardAndCloseIgnoringErrors(rsp.Body) 60 statusCode = rsp.StatusCode 61 body = MustParseStream(rsp.Body) 62 return 63 }