client.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. Copyright 2017 The Kubernetes 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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package openapi
  14. import (
  15. "context"
  16. "encoding/json"
  17. "strings"
  18. "k8s.io/client-go/rest"
  19. "k8s.io/kube-openapi/pkg/handler3"
  20. )
  21. type Client interface {
  22. Paths() (map[string]GroupVersion, error)
  23. }
  24. type client struct {
  25. // URL includes the `hash` query param to take advantage of cache busting
  26. restClient rest.Interface
  27. }
  28. func NewClient(restClient rest.Interface) Client {
  29. return &client{
  30. restClient: restClient,
  31. }
  32. }
  33. func (c *client) Paths() (map[string]GroupVersion, error) {
  34. data, err := c.restClient.Get().
  35. AbsPath("/openapi/v3").
  36. Do(context.TODO()).
  37. Raw()
  38. if err != nil {
  39. return nil, err
  40. }
  41. discoMap := &handler3.OpenAPIV3Discovery{}
  42. err = json.Unmarshal(data, discoMap)
  43. if err != nil {
  44. return nil, err
  45. }
  46. // Create GroupVersions for each element of the result
  47. result := map[string]GroupVersion{}
  48. for k, v := range discoMap.Paths {
  49. // If the server returned a URL rooted at /openapi/v3, preserve any additional client-side prefix.
  50. // If the server returned a URL not rooted at /openapi/v3, treat it as an actual server-relative URL.
  51. // See https://github.com/kubernetes/kubernetes/issues/117463 for details
  52. useClientPrefix := strings.HasPrefix(v.ServerRelativeURL, "/openapi/v3")
  53. result[k] = newGroupVersion(c, v, useClientPrefix)
  54. }
  55. return result, nil
  56. }