|
| 1 | +// Copyright 2020 Tetrate |
| 2 | +// |
| 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 | +package transport |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "net/http" |
| 20 | + |
| 21 | + "github.com/tetratelabs/getenvoy/pkg/version" |
| 22 | +) |
| 23 | + |
| 24 | +var ( |
| 25 | + cliUserAgent = fmt.Sprintf("GetEnvoy/%s", version.Build.Version) |
| 26 | + defaultClient = NewClient(AddUserAgent(cliUserAgent)) |
| 27 | +) |
| 28 | + |
| 29 | +// Option represents an argument of NewClient |
| 30 | +type Option func(http.RoundTripper) http.RoundTripper |
| 31 | + |
| 32 | +// NewClient returns HTTP client for use of GetEnvoy CLI. |
| 33 | +func NewClient(opts ...Option) *http.Client { |
| 34 | + tr := http.DefaultTransport |
| 35 | + for _, opt := range opts { |
| 36 | + tr = opt(tr) |
| 37 | + } |
| 38 | + client := &http.Client{Transport: tr} |
| 39 | + return client |
| 40 | +} |
| 41 | + |
| 42 | +// AddUserAgent returns Option that adds passed user-agent to every requests. |
| 43 | +// It should be passed as an argument of NewClient. |
| 44 | +func AddUserAgent(ua string) Option { |
| 45 | + return func(tr http.RoundTripper) http.RoundTripper { |
| 46 | + return &funcTripper{roundTrip: func(r *http.Request) (*http.Response, error) { |
| 47 | + r.Header.Add("User-Agent", ua) |
| 48 | + return tr.RoundTrip(r) |
| 49 | + }} |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +type funcTripper struct { |
| 54 | + roundTrip func(*http.Request) (*http.Response, error) |
| 55 | +} |
| 56 | + |
| 57 | +func (f funcTripper) RoundTrip(r *http.Request) (*http.Response, error) { |
| 58 | + return f.roundTrip(r) |
| 59 | +} |
| 60 | + |
| 61 | +// Get is thin wrapper of net/http.Get. |
| 62 | +func Get(url string) (*http.Response, error) { |
| 63 | + return defaultClient.Get(url) |
| 64 | +} |
0 commit comments