endpoints.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package secretmanager
  13. import (
  14. "encoding/json"
  15. "fmt"
  16. "net/http"
  17. )
  18. // EndpointsURI is the URI for getting the actual Cloud.ru API endpoints.
  19. const EndpointsURI = "https://api.cloud.ru/endpoints"
  20. // EndpointsResponse is a response from the Cloud.ru API.
  21. type EndpointsResponse struct {
  22. // Endpoints contains the list of actual API addresses of Cloud.ru products.
  23. Endpoints []Endpoint `json:"endpoints"`
  24. }
  25. // Endpoint is a product API address.
  26. type Endpoint struct {
  27. ID string `json:"id"`
  28. Address string `json:"address"`
  29. }
  30. // GetEndpoints returns the actual Cloud.ru API endpoints.
  31. func GetEndpoints(url string) (*EndpointsResponse, error) {
  32. req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
  33. if err != nil {
  34. return nil, fmt.Errorf("construct HTTP request for cloud.ru endpoints: %w", err)
  35. }
  36. resp, err := http.DefaultClient.Do(req)
  37. if err != nil {
  38. return nil, fmt.Errorf("get cloud.ru endpoints: %w", err)
  39. }
  40. defer func() {
  41. _ = resp.Body.Close()
  42. }()
  43. if resp.StatusCode != http.StatusOK {
  44. return nil, fmt.Errorf("get cloud.ru endpoints: unexpected status code %d", resp.StatusCode)
  45. }
  46. var endpoints EndpointsResponse
  47. if err = json.NewDecoder(resp.Body).Decode(&endpoints); err != nil {
  48. return nil, fmt.Errorf("decode cloud.ru endpoints: %w", err)
  49. }
  50. return &endpoints, nil
  51. }
  52. // Get returns the API address of the product by its ID.
  53. // If the product is not found, the function returns nil.
  54. func (er *EndpointsResponse) Get(id string) *Endpoint {
  55. for i := range er.Endpoints {
  56. if er.Endpoints[i].ID == id {
  57. return &er.Endpoints[i]
  58. }
  59. }
  60. return nil
  61. }