github.com/kaydxh/golang@v0.0.131/go/net/http/http_transport.proxy.go (about) 1 /* 2 *Copyright (c) 2023, kaydxh 3 * 4 *Permission is hereby granted, free of charge, to any person obtaining a copy 5 *of this software and associated documentation files (the "Software"), to deal 6 *in the Software without restriction, including without limitation the rights 7 *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 *copies of the Software, and to permit persons to whom the Software is 9 *furnished to do so, subject to the following conditions: 10 * 11 *The above copyright notice and this permission notice shall be included in all 12 *copies or substantial portions of the Software. 13 * 14 *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 *SOFTWARE. 21 */ 22 package http 23 24 import ( 25 "crypto/tls" 26 "net" 27 "net/http" 28 "net/url" 29 "time" 30 31 resolve_ "github.com/kaydxh/golang/go/net/resolver/resolve" 32 logs_ "github.com/kaydxh/golang/pkg/logs" 33 ) 34 35 func RequestWithContextProxy(req *http.Request, proxy *Proxy) *http.Request { 36 if proxy == nil { 37 return req 38 } 39 return req.WithContext(WithContextProxy(req.Context(), proxy)) 40 } 41 42 func ProxyFuncFromContextOrEnvironment(req *http.Request) (*url.URL, error) { 43 logger := logs_.GetLogger(req.Context()) 44 proxy := FromContextProxy(req.Context()) 45 if proxy == nil || proxy.ProxyUrl == "" { 46 return http.ProxyFromEnvironment(req) 47 } 48 defer func() { 49 logger.Infof("http request proxy: %v", proxy) 50 }() 51 52 proxyUrl, err := ParseProxyUrl(proxy.ProxyUrl) 53 if err != nil { 54 return nil, err 55 } 56 if proxyUrl == nil { 57 return nil, nil 58 } 59 60 if proxy.ProxyTarget == "" { 61 return proxyUrl, nil 62 } 63 64 // replace host of proxy if target of proxy if resolved 65 address, err := resolve_.ResolveOne(req.Context(), proxy.ProxyTarget) 66 if err != nil { 67 return nil, err 68 } 69 if address.Addr != "" { 70 proxyUrl.Host = address.Addr 71 } 72 proxy.ProxyAddrResolved = address 73 74 return proxyUrl, nil 75 } 76 77 var DefaultTransportInsecureWithProxy http.RoundTripper = &http.Transport{ 78 Proxy: ProxyFuncFromContextOrEnvironment, 79 DialContext: (&net.Dialer{ 80 Timeout: 30 * time.Second, 81 KeepAlive: 30 * time.Second, 82 }).DialContext, 83 ForceAttemptHTTP2: true, 84 MaxIdleConns: 100, 85 IdleConnTimeout: 90 * time.Second, 86 TLSHandshakeTimeout: 10 * time.Second, 87 ExpectContinueTimeout: 1 * time.Second, 88 // skip verify for https 89 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, 90 }