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