gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/net/context/ctxhttp/ctxhttp.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package ctxhttp provides helper functions for performing context-aware HTTP requests. 6 package ctxhttp // import "gitee.com/ks-custle/core-gm/net/context/ctxhttp" 7 8 import ( 9 "context" 10 "io" 11 "net/url" 12 "strings" 13 14 http "gitee.com/ks-custle/core-gm/gmhttp" 15 ) 16 17 // Do sends an HTTP request with the provided http.Client and returns 18 // an HTTP response. 19 // 20 // If the client is nil, http.DefaultClient is used. 21 // 22 // The provided ctx must be non-nil. If it is canceled or times out, 23 // ctx.Err() will be returned. 24 func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { 25 if client == nil { 26 client = http.DefaultClient 27 } 28 resp, err := client.Do(req.WithContext(ctx)) 29 // If we got an error, and the context has been canceled, 30 // the context's error is probably more useful. 31 if err != nil { 32 select { 33 case <-ctx.Done(): 34 err = ctx.Err() 35 default: 36 } 37 } 38 return resp, err 39 } 40 41 // Get issues a GET request via the Do function. 42 func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { 43 req, err := http.NewRequest("GET", url, nil) 44 if err != nil { 45 return nil, err 46 } 47 return Do(ctx, client, req) 48 } 49 50 // Head issues a HEAD request via the Do function. 51 func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { 52 req, err := http.NewRequest("HEAD", url, nil) 53 if err != nil { 54 return nil, err 55 } 56 return Do(ctx, client, req) 57 } 58 59 // Post issues a POST request via the Do function. 60 func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { 61 req, err := http.NewRequest("POST", url, body) 62 if err != nil { 63 return nil, err 64 } 65 req.Header.Set("Content-Type", bodyType) 66 return Do(ctx, client, req) 67 } 68 69 // PostForm issues a POST request via the Do function. 70 func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { 71 return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) 72 }