github.com/azure-devops-engineer/helm@v3.0.0-alpha.2+incompatible/pkg/getter/httpgetter.go (about) 1 /* 2 Copyright The Helm Authors. 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 */ 15 16 package getter 17 18 import ( 19 "bytes" 20 "io" 21 "net/http" 22 23 "github.com/pkg/errors" 24 25 "helm.sh/helm/pkg/tlsutil" 26 "helm.sh/helm/pkg/urlutil" 27 ) 28 29 // HTTPGetter is the efault HTTP(/S) backend handler 30 type HTTPGetter struct { 31 client *http.Client 32 opts options 33 } 34 35 //Get performs a Get from repo.Getter and returns the body. 36 func (g *HTTPGetter) Get(href string) (*bytes.Buffer, error) { 37 return g.get(href) 38 } 39 40 func (g *HTTPGetter) get(href string) (*bytes.Buffer, error) { 41 buf := bytes.NewBuffer(nil) 42 43 // Set a helm specific user agent so that a repo server and metrics can 44 // separate helm calls from other tools interacting with repos. 45 req, err := http.NewRequest("GET", href, nil) 46 if err != nil { 47 return buf, err 48 } 49 // req.Header.Set("User-Agent", "Helm/"+strings.TrimPrefix(version.GetVersion(), "v")) 50 if g.opts.userAgent != "" { 51 req.Header.Set("User-Agent", g.opts.userAgent) 52 } 53 54 if g.opts.username != "" && g.opts.password != "" { 55 req.SetBasicAuth(g.opts.username, g.opts.password) 56 } 57 58 resp, err := g.client.Do(req) 59 if err != nil { 60 return buf, err 61 } 62 if resp.StatusCode != 200 { 63 return buf, errors.Errorf("failed to fetch %s : %s", href, resp.Status) 64 } 65 66 _, err = io.Copy(buf, resp.Body) 67 resp.Body.Close() 68 return buf, err 69 } 70 71 // NewHTTPGetter constructs a valid http/https client as a Getter 72 func NewHTTPGetter(options ...Option) (Getter, error) { 73 var client HTTPGetter 74 75 for _, opt := range options { 76 opt(&client.opts) 77 } 78 79 if client.opts.certFile != "" && client.opts.keyFile != "" { 80 tlsConf, err := tlsutil.NewClientTLS(client.opts.certFile, client.opts.keyFile, client.opts.caFile) 81 if err != nil { 82 return &client, errors.Wrap(err, "can't create TLS config for client") 83 } 84 tlsConf.BuildNameToCertificate() 85 86 sni, err := urlutil.ExtractHostname(client.opts.url) 87 if err != nil { 88 return &client, err 89 } 90 tlsConf.ServerName = sni 91 92 client.client = &http.Client{ 93 Transport: &http.Transport{ 94 TLSClientConfig: tlsConf, 95 Proxy: http.ProxyFromEnvironment, 96 }, 97 } 98 } else { 99 client.client = http.DefaultClient 100 } 101 102 return &client, nil 103 }