| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
// Copyright (c) 2021 The Jaeger Authors. |
| 5 |
// Copyright (c) 2017 Uber Technologies, Inc. |
| 6 |
// |
| 7 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 |
// you may not use this file except in compliance with the License. |
| 9 |
// You may obtain a copy of the License at |
| 10 |
// |
| 11 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 12 |
// |
| 13 |
// Unless required by applicable law or agreed to in writing, software |
| 14 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 15 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 |
// See the License for the specific language governing permissions and |
| 17 |
// limitations under the License. |
| 18 |
|
| 19 |
package testutils // import "go.opentelemetry.io/contrib/samplers/jaegerremote/internal/testutils" |
| 20 |
|
| 21 |
import ( |
| 22 |
"context" |
| 23 |
"encoding/json" |
| 24 |
"fmt" |
| 25 |
"io" |
| 26 |
"net/http" |
| 27 |
) |
| 28 |
|
| 29 |
// getJSON makes an HTTP call to the specified URL and parses the returned JSON into `out`. |
| 30 |
func getJSON(ctx context.Context, url string, out any) error { |
| 31 |
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) |
| 32 |
if err != nil { |
| 33 |
return err |
| 34 |
} |
| 35 |
resp, err := http.DefaultClient.Do(req) |
| 36 |
if err != nil { |
| 37 |
return err |
| 38 |
} |
| 39 |
return readJSON(resp, out) |
| 40 |
} |
| 41 |
|
| 42 |
// readJSON reads JSON from http.Response and parses it into `out`. |
| 43 |
func readJSON(resp *http.Response, out any) error { |
| 44 |
defer resp.Body.Close() |
| 45 |
|
| 46 |
if resp.StatusCode >= 400 { |
| 47 |
body, err := io.ReadAll(resp.Body) |
| 48 |
if err != nil { |
| 49 |
return err |
| 50 |
} |
| 51 |
|
| 52 |
return fmt.Errorf("status code: %d, body: %s", resp.StatusCode, body) |
| 53 |
} |
| 54 |
|
| 55 |
if out == nil { |
| 56 |
_, err := io.Copy(io.Discard, resp.Body) |
| 57 |
if err != nil { |
| 58 |
return err |
| 59 |
} |
| 60 |
return nil |
| 61 |
} |
| 62 |
|
| 63 |
decoder := json.NewDecoder(resp.Body) |
| 64 |
return decoder.Decode(out) |
| 65 |
} |