| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package httpx |
| 4 | |
| 5 | import ( |
| 6 | "crypto/tls" |
| 7 | "net/http" |
| 8 | "strings" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | func noRedirect(*http.Request, []*http.Request) error { |
| 13 | return http.ErrUseLastResponse |
| 14 | } |
| 15 | |
| 16 | func APIClient(timeout time.Duration) *http.Client { |
| 17 | return &http.Client{Timeout: timeout} |
| 18 | } |
| 19 | |
| 20 | func NoProxyClient(timeout time.Duration) *http.Client { |
| 21 | transport := cloneDefaultTransport() |
| 22 | transport.Proxy = nil |
| 23 | |
| 24 | return &http.Client{ |
| 25 | Timeout: timeout, |
| 26 | Transport: transport, |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | func VaultClient(timeout time.Duration) *http.Client { |
| 31 | return &http.Client{ |
| 32 | Timeout: timeout, |
| 33 | CheckRedirect: noRedirect, |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | func VaultInsecureClient(timeout time.Duration) *http.Client { |
| 38 | transport := cloneDefaultTransport() |
| 39 | if transport.TLSClientConfig != nil { |
| 40 | transport.TLSClientConfig = transport.TLSClientConfig.Clone() |
| 41 | } else { |
| 42 | transport.TLSClientConfig = &tls.Config{} |
| 43 | } |
| 44 | transport.TLSClientConfig.InsecureSkipVerify = true |
| 45 | |
| 46 | return &http.Client{ |
| 47 | Timeout: timeout, |
| 48 | Transport: transport, |
| 49 | CheckRedirect: noRedirect, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func cloneDefaultTransport() *http.Transport { |
| 54 | transport, ok := http.DefaultTransport.(*http.Transport) |
| 55 | if !ok || transport == nil { |
| 56 | return &http.Transport{} |
| 57 | } |
| 58 | return transport.Clone() |
| 59 | } |
| 60 | |
| 61 | func TruncateBody(body []byte) string { |
| 62 | const maxLen = 200 |
| 63 | s := strings.TrimSpace(string(body)) |
| 64 | if len(s) > maxLen { |
| 65 | return s[:maxLen] + "..." |
| 66 | } |
| 67 | return s |
| 68 | } |