本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.3KB

  1. // Copyright 2014 Google Inc. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package internal
  5. // This file has code for accessing metadata.
  6. //
  7. // References:
  8. // https://cloud.google.com/compute/docs/metadata
  9. import (
  10. "fmt"
  11. "io/ioutil"
  12. "net/http"
  13. "net/url"
  14. )
  15. const (
  16. metadataHost = "metadata"
  17. metadataPath = "/computeMetadata/v1/"
  18. )
  19. var (
  20. metadataRequestHeaders = http.Header{
  21. "Metadata-Flavor": []string{"Google"},
  22. }
  23. )
  24. // TODO(dsymonds): Do we need to support default values, like Python?
  25. func mustGetMetadata(key string) []byte {
  26. b, err := getMetadata(key)
  27. if err != nil {
  28. panic(fmt.Sprintf("Metadata fetch failed for '%s': %v", key, err))
  29. }
  30. return b
  31. }
  32. func getMetadata(key string) ([]byte, error) {
  33. // TODO(dsymonds): May need to use url.Parse to support keys with query args.
  34. req := &http.Request{
  35. Method: "GET",
  36. URL: &url.URL{
  37. Scheme: "http",
  38. Host: metadataHost,
  39. Path: metadataPath + key,
  40. },
  41. Header: metadataRequestHeaders,
  42. Host: metadataHost,
  43. }
  44. resp, err := http.DefaultClient.Do(req)
  45. if err != nil {
  46. return nil, err
  47. }
  48. defer resp.Body.Close()
  49. if resp.StatusCode != 200 {
  50. return nil, fmt.Errorf("metadata server returned HTTP %d", resp.StatusCode)
  51. }
  52. return ioutil.ReadAll(resp.Body)
  53. }
上海开阖软件有限公司 沪ICP备12045867号-1