func systemInfoSuggestsGCE() bool {
	if runtime.GOOS != "linux" {
		return false
	}
	slurp, _ := ioutil.ReadFile("/sys/class/dmi/id/product_name")
	name := strings.TrimSpace(string(slurp))
	return name == "Google" || name == "Google Compute Engine"
}
systemInfoSuggestsGCE reports whether the local system (without
doing network requests) suggests that we're running on GCE. If this
returns true, testOnGCE tries a bit harder to reach its metadata
server.
package metadata  
import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"os"
	"runtime"
	"strings"
	"sync"
	"time"
)
const (
	metadataIP = "169.254.169.254"
	metadataHostEnv = "GCE_METADATA_HOST"
	userAgent = "gcloud-golang/0.1"
)
type cachedValue struct {
	k    string
	trim bool
	mu   sync.Mutex
	v    string
}
var (
	projID  = &cachedValue{k: "project/project-id", trim: true}
	projNum = &cachedValue{k: "project/numeric-project-id", trim: true}
	instID  = &cachedValue{k: "instance/id", trim: true}
)
var defaultClient = &Client{hc: &http.Client{
	Transport: &http.Transport{
		Dial: (&net.Dialer{
			Timeout:   2 * time.Second,
			KeepAlive: 30 * time.Second,
		}).Dial,
	},
}}
type NotDefinedError string
func (suffix NotDefinedError) Error() string {
	return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix))
}
func (c *cachedValue) get(cl *Client) (v string, err error) {
	defer c.mu.Unlock()
	c.mu.Lock()
	if c.v != "" {
		return c.v, nil
	}
	if c.trim {
		v, err = cl.getTrimmed(c.k)
	} else {
		v, err = cl.Get(c.k)
	}
	if err == nil {
		c.v = v
	}
	return
}
var (
	onGCEOnce sync.Once
	onGCE     bool
)
func OnGCE() bool {
	onGCEOnce.Do(initOnGCE)
	return onGCE
}
func initOnGCE() {
	onGCE = testOnGCE()
}
func testOnGCE() bool {
	if os.Getenv(metadataHostEnv) != "" {
		return true
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	resc := make(chan bool, 2)
	go func() {
		req, _ := http.NewRequest("GET", "http://"+metadataIP, nil)
		req.Header.Set("User-Agent", userAgent)
		res, err := defaultClient.hc.Do(req.WithContext(ctx))
		if err != nil {
			resc <- false
			return
		}
		defer res.Body.Close()
		resc <- res.Header.Get("Metadata-Flavor") == "Google"
	}()
	go func() {
		addrs, err := net.DefaultResolver.LookupHost(ctx, "metadata.google.internal")
		if err != nil || len(addrs) == 0 {
			resc <- false
			return
		}
		resc <- strsContains(addrs, metadataIP)
	}()
	tryHarder := systemInfoSuggestsGCE()
	if tryHarder {
		res := <-resc
		if res {
			return true
		}
		timer := time.NewTimer(5 * time.Second)
		defer timer.Stop()
		select {
		case res = <-resc:
			return res
		case <-timer.C:
			return false
		}
	}
	return <-resc
}