metadata.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. "log"
  13. "net/http"
  14. "net/url"
  15. )
  16. const (
  17. metadataHost = "metadata"
  18. metadataPath = "/computeMetadata/v1/"
  19. )
  20. var (
  21. metadataRequestHeaders = http.Header{
  22. "Metadata-Flavor": []string{"Google"},
  23. }
  24. )
  25. // TODO(dsymonds): Do we need to support default values, like Python?
  26. func mustGetMetadata(key string) []byte {
  27. b, err := getMetadata(key)
  28. if err != nil {
  29. log.Fatalf("Metadata fetch failed: %v", err)
  30. }
  31. return b
  32. }
  33. func getMetadata(key string) ([]byte, error) {
  34. // TODO(dsymonds): May need to use url.Parse to support keys with query args.
  35. req := &http.Request{
  36. Method: "GET",
  37. URL: &url.URL{
  38. Scheme: "http",
  39. Host: metadataHost,
  40. Path: metadataPath + key,
  41. },
  42. Header: metadataRequestHeaders,
  43. Host: metadataHost,
  44. }
  45. resp, err := http.DefaultClient.Do(req)
  46. if err != nil {
  47. return nil, err
  48. }
  49. defer resp.Body.Close()
  50. if resp.StatusCode != 200 {
  51. return nil, fmt.Errorf("metadata server returned HTTP %d", resp.StatusCode)
  52. }
  53. return ioutil.ReadAll(resp.Body)
  54. }