当前位置: 首页>>代码示例>>Golang>>正文


Golang os.LookupEnv函数代码示例

本文整理汇总了Golang中os.LookupEnv函数的典型用法代码示例。如果您正苦于以下问题:Golang LookupEnv函数的具体用法?Golang LookupEnv怎么用?Golang LookupEnv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了LookupEnv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	flag.Parse()

	username, ok := os.LookupEnv(teamcityAPIUserEnv)
	if !ok {
		log.Fatalf("teamcity API username environment variable %s is not set", teamcityAPIUserEnv)
	}
	password, ok := os.LookupEnv(teamcityAPIPasswordEnv)
	if !ok {
		log.Fatalf("teamcity API password environment variable %s is not set", teamcityAPIPasswordEnv)
	}
	importPaths := gotool.ImportPaths([]string{"github.com/cockroachdb/cockroach/..."})

	client := teamcity.New("teamcity.cockroachdb.com", username, password)
	// Queue a build per configuration per package.
	for _, params := range []map[string]string{
		{}, // uninstrumented
		{"env.GOFLAGS": "-race"},
		{"env.TAGS": "deadlock"},
	} {
		for _, importPath := range importPaths {
			params["env.PKG"] = importPath
			build, err := client.QueueBuild(*buildTypeID, *branchName, params)
			if err != nil {
				log.Fatalf("failed to create teamcity build (*buildTypeID=%s *branchName=%s, params=%+v): %s", *buildTypeID, *branchName, params, err)
			}
			log.Printf("created teamcity build (*buildTypeID=%s *branchName=%s, params=%+v): %s", *buildTypeID, *branchName, params, build)
		}
	}
}
开发者ID:bdarnell,项目名称:cockroach,代码行数:30,代码来源:main.go

示例2: main

func main() {
	flag.Parse()

	serverURL, ok := os.LookupEnv(teamcityServerURLEnv)
	if !ok {
		log.Fatalf("teamcity server URL environment variable %s is not set", teamcityServerURLEnv)
	}
	u, err := url.Parse(serverURL)
	if err != nil {
		log.Fatal(err)
	}
	username, ok := os.LookupEnv(teamcityAPIUserEnv)
	if !ok {
		log.Fatalf("teamcity API username environment variable %s is not set", teamcityAPIUserEnv)
	}
	password, ok := os.LookupEnv(teamcityAPIPasswordEnv)
	if !ok {
		log.Fatalf("teamcity API password environment variable %s is not set", teamcityAPIPasswordEnv)
	}
	client := teamcity.New(u.Host, username, password)
	runTC(func(properties map[string]string) {
		build, err := client.QueueBuild(*buildTypeID, *branchName, properties)
		if err != nil {
			log.Fatalf("failed to create teamcity build (*buildTypeID=%s *branchName=%s, properties=%+v): %s", *buildTypeID, *branchName, properties, err)
		}
		log.Printf("created teamcity build (*buildTypeID=%s *branchName=%s, properties=%+v): %s", *buildTypeID, *branchName, properties, build)
	})
}
开发者ID:jmptrader,项目名称:cockroach,代码行数:28,代码来源:main.go

示例3: main

// Right now, this is a really simple proxy that uses defaults
// nearly everywhere, and does nothing other than blindly proxy a
// request to a single server.
func main() {

	bind, provided := os.LookupEnv("BIND_ADDR")
	if !provided {
		bind = ":8090"
	}
	log.Println("Binding to", bind)

	proxyHost, provided := os.LookupEnv("PROXY_ADDR")
	if !provided {
		proxyHost = "127.0.0.1:8080"
	}
	log.Println("Proxying host", proxyHost)

	proxyPath, provided := os.LookupEnv("PROXY_PATH")
	if !provided {
		proxyPath = "/"
	}
	log.Println("Proxy Path", proxyPath)

	proxy := httputil.NewSingleHostReverseProxy(&url.URL{Host: proxyHost, Path: proxyPath, Scheme: "http"})

	if err := http.ListenAndServe(bind, proxy); err != nil {
		log.Panic("Could not start proxy", err)
	}
}
开发者ID:fcrepo4-labs,项目名称:fcrepo-api-x,代码行数:29,代码来源:proxy.go

示例4: InitializeAppSensorRestClient

// read environment variables for data for http client construction
func InitializeAppSensorRestClient() {

	RestUrl, urlExists = os.LookupEnv("APPSENSOR_REST_ENGINE_URL")
	RestHeaderName, nameExists = os.LookupEnv("APPSENSOR_CLIENT_APPLICATION_ID_HEADER_NAME")
	RestHeaderValue, valueExists = os.LookupEnv("APPSENSOR_CLIENT_APPLICATION_ID_HEADER_VALUE")
	ClientIp, ipExists = os.LookupEnv("APPSENSOR_CLIENT_APPLICATION_IP_ADDRESS")

	missingFields := make([]string, 0)

	if !urlExists {
		missingFields = append(missingFields, "APPSENSOR_REST_ENGINE_URL")
	}

	if !nameExists {
		glog.Info("The APPSENSOR_CLIENT_APPLICATION_ID_HEADER_NAME env var not set, using default value")
		RestHeaderName = "X-Appsensor-Client-Application-Name"
	}

	if !valueExists {
		missingFields = append(missingFields, "APPSENSOR_CLIENT_APPLICATION_ID_HEADER_VALUE")
	}

	if !ipExists {
		missingFields = append(missingFields, "APPSENSOR_CLIENT_APPLICATION_ID_HEADER_VALUE")
	}

	if len(missingFields) > 0 {
		log.Fatal("The following environment variable(s) must be populated: [ " + strings.Join(missingFields, " , ") + " ]")
	}

	glog.Info("Rest client information configured properly.")

}
开发者ID:ProZachJ,项目名称:appsensor-reverse-proxy,代码行数:34,代码来源:data.go

示例5: KubemarkTest

func KubemarkTest() error {
	// Stop previous run
	err := finishRunning("Stop kubemark", exec.Command("./test/kubemark/stop-kubemark.sh"))
	if err != nil {
		return err
	}
	// If we tried to bring the Kubemark cluster up, make a courtesy
	// attempt to bring it down so we're not leaving resources around.
	//
	// TODO: We should try calling stop-kubemark exactly once. Though to
	// stop the leaking resources for now, we want to be on the safe side
	// and call it explictly in defer if the other one is not called.
	defer xmlWrap("Deferred Stop kubemark", func() error {
		return finishRunning("Stop kubemark", exec.Command("./test/kubemark/stop-kubemark.sh"))
	})

	// Start new run
	backups := []string{"NUM_NODES", "MASTER_SIZE"}
	for _, item := range backups {
		old, present := os.LookupEnv(item)
		if present {
			defer os.Setenv(item, old)
		} else {
			defer os.Unsetenv(item)
		}
	}
	os.Setenv("NUM_NODES", os.Getenv("KUBEMARK_NUM_NODES"))
	os.Setenv("MASTER_SIZE", os.Getenv("KUBEMARK_MASTER_SIZE"))
	err = xmlWrap("Start kubemark", func() error {
		return finishRunning("Start kubemark", exec.Command("./test/kubemark/start-kubemark.sh"))
	})
	if err != nil {
		return err
	}

	// Run kubemark tests
	focus, present := os.LookupEnv("KUBEMARK_TESTS")
	if !present {
		focus = "starting\\s30\\pods"
	}
	test_args := os.Getenv("KUBEMARK_TEST_ARGS")

	err = finishRunning("Run kubemark tests", exec.Command("./test/kubemark/run-e2e-tests.sh", "--ginkgo.focus="+focus, test_args))
	if err != nil {
		return err
	}

	err = xmlWrap("Stop kubemark", func() error {
		return finishRunning("Stop kubemark", exec.Command("./test/kubemark/stop-kubemark.sh"))
	})
	if err != nil {
		return err
	}
	return nil
}
开发者ID:Q-Lee,项目名称:kubernetes,代码行数:55,代码来源:e2e.go

示例6: main

func main() {
	tz := "US/Pacific"
	if cattz, ok := os.LookupEnv("CATZ"); ok {
		tz = cattz
	} else {
		stdtz, ok := os.LookupEnv("TZ")
		if ok {
			tz = stdtz
		}
	}
	srcTZ := flag.String("srctz", "UTC", "input time zone")
	destTZ := flag.String("outtz", tz, "output time zone (defaults to $CATZ or $TZ env if available)")
	debug := flag.Bool("d", false, "enable debug logging")
	timeFormat := flag.String("t", "%Y-%m-%d %H", "strftime format")
	first := flag.Bool("first", false, "only replace first timestamp match per line")
	flag.Parse()

	sourceLocation, err := time.LoadLocation(*srcTZ)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR input TZ %s not known\n", *srcTZ)
		os.Exit(1)
	}

	destLocation, err := time.LoadLocation(*destTZ)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR output TZ %s not known\n", *destTZ)
		os.Exit(1)
	}
	c := &controller{
		srcLoc:  sourceLocation,
		destLoc: destLocation,
		buf:     &bytes.Buffer{},
		debug:   *debug,
	}
	// verify we know how to handle the time format
	c.format, err = strftime.New(*timeFormat)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR time format [%s] had problem converting to go format%s\n", *timeFormat, err)
		os.Exit(1)
	}
	err = c.strftimeToRE(*timeFormat)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR time format [%s] had problem to regex %s\n", *timeFormat, err)
		os.Exit(1)
	}
	// only replace first timestamp occurance, or replace all
	if *first {
		c.matchLimit = 1
	} else {
		c.matchLimit = -1
	}

	os.Exit(c.execute())
}
开发者ID:billhathaway,项目名称:catz,代码行数:54,代码来源:main.go

示例7: processEnv

func processEnv() {
	if val, exist := os.LookupEnv(COMMNAND_BUS_URL_ENV); exist {
		commandBusUrl = val
	}
	if val, exist := os.LookupEnv(QUEUE_NAME_ENV); exist {
		queueName = val
	}
	if val, exist := os.LookupEnv(LISTENER_PORT_ENV); exist {
		listenerPort = val
	}
}
开发者ID:ondaway,项目名称:poc,代码行数:11,代码来源:publisher.go

示例8: main

func main() {
	home, ok := os.LookupEnv("HOME")
	if !ok {
		log.Fatalf("$HOME not set")
	}
	visual, ok := os.LookupEnv("EDITOR")
	if !ok {
		log.Fatalf("$EDITOR not set")
	}
	year, month, day := time.Now().Date()
	jf := fmt.Sprintf("%s/journal/%d.%d.%d.md", home, day, month, year)
	var f *os.File
	if _, err := os.Stat(jf); os.IsNotExist(err) {
		f, err = os.Create(jf)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Fprintf(f, "%s\n\n", time.Now().Format(time.UnixDate))
	} else if err == nil {
		f, err = os.OpenFile(jf, os.O_RDWR, 0644)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Fatal(err)
	}
	ohash, err := hash(f)
	if err != nil {
		log.Fatal(err)
	}
	// Open editor
	cmd := exec.Command(visual, f.Name())
	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
	// Generate post-edit hash
	nhash, err := hash(f)
	// If hashes are different, ask for commit message
	if ohash != nhash {
		// Add file to git
		cmd := exec.Command("git", "-C", filepath.Dir(f.Name()), "add", f.Name())
		if err := cmd.Run(); err != nil {
			log.Fatal(err)
		}
		// Read commit message from user
		fmt.Printf("Enter a summary and then press ^D\n\n")
		// Commit file to git
		cmd = exec.Command("git", "-C", filepath.Dir(f.Name()), "commit", "--file", "-")
		cmd.Stdin = os.Stdin
		if err := cmd.Run(); err != nil {
			log.Fatal(err)
		}
	}
}
开发者ID:cptaffe,项目名称:journal,代码行数:54,代码来源:journal.go

示例9: init

func init() {
	if envPrefix, ok := os.LookupEnv("RIP_PREFIX"); ok {
		ripPrefix = envPrefix
		ripPattern = envPrefix + "0"
	}
	if envPattern, ok := os.LookupEnv("RIP_PATTERN"); ok {
		ripPattern = envPattern
	}
	if envRegex, ok := os.LookupEnv("RIP_REGEX"); ok {
		ripRegex = envRegex
	}
}
开发者ID:icholy,项目名称:rip,代码行数:12,代码来源:rip.go

示例10: verifyEnvironment

// Verifies that all environment variables are set. Fails if not all are set by
// returning an error.
func verifyEnvironment() error {
	_, cache := os.LookupEnv(cache_path_var)
	_, whost := os.LookupEnv(worker_host_var)
	_, wport := os.LookupEnv(worker_port_var)

	if !cache || !whost || !wport {
		return fmt.Errorf("Application settings missing!\n"+
			"Please set the %s, %s and %s environment variables.",
			cache_path_var, worker_host_var, worker_port_var)
	}

	return nil
}
开发者ID:AnalysisBotsPlatform,项目名称:worker,代码行数:15,代码来源:main.go

示例11: main

func main() {
	flag.Parse()

	serverURL, ok := os.LookupEnv(teamcityServerURLEnv)
	if !ok {
		log.Fatalf("teamcity server URL environment variable %s is not set", teamcityServerURLEnv)
	}
	u, err := url.Parse(serverURL)
	if err != nil {
		log.Fatal(err)
	}
	username, ok := os.LookupEnv(teamcityAPIUserEnv)
	if !ok {
		log.Fatalf("teamcity API username environment variable %s is not set", teamcityAPIUserEnv)
	}
	password, ok := os.LookupEnv(teamcityAPIPasswordEnv)
	if !ok {
		log.Fatalf("teamcity API password environment variable %s is not set", teamcityAPIPasswordEnv)
	}
	importPaths := gotool.ImportPaths([]string{"github.com/cockroachdb/cockroach/pkg/..."})

	client := teamcity.New(u.Host, username, password)
	// Queue a build per configuration per package.
	for _, params := range []map[string]string{
		{}, // uninstrumented
		{"env.GOFLAGS": "-race"},
		{tagsKey: "deadlock"},
	} {
		if tags, ok := params[tagsKey]; ok {
			params[tagsKey] = strings.Join([]string{tags, stressTag}, " ")
		} else {
			params[tagsKey] = stressTag
		}

		for _, propEvalKV := range []bool{true, false} {
			params["env.COCKROACH_PROPOSER_EVALUATED_KV"] = strconv.FormatBool(propEvalKV)

			for _, importPath := range importPaths {
				params["env.PKG"] = importPath

				build, err := client.QueueBuild(*buildTypeID, *branchName, params)
				if err != nil {
					log.Fatalf("failed to create teamcity build (*buildTypeID=%s *branchName=%s, params=%+v): %s", *buildTypeID, *branchName, params, err)
				}
				log.Printf("created teamcity build (*buildTypeID=%s *branchName=%s, params=%+v): %s", *buildTypeID, *branchName, params, build)
			}
		}
	}
}
开发者ID:veteranlu,项目名称:cockroach,代码行数:49,代码来源:main.go

示例12: CreateDockerfile

func CreateDockerfile(tmplPath, baseImage, exprID string, serverPort int) (string, error) {
	// Docker likes absolute paths for Dockerfiles.
	dockerfilePath := filepath.Join(filepath.Dir(tmplPath), fmt.Sprintf("Dockerfile_%s", exprID))
	if !strings.HasPrefix(dockerfilePath, "/") {
		v, ok := os.LookupEnv("PWD")
		if !ok {
			return "", fmt.Errorf("Envvar PWD not set.")
		}
		dockerfilePath = filepath.Join(v, dockerfilePath)
	}
	t, err := template.New(filepath.Base(tmplPath)).ParseFiles(tmplPath)
	if err != nil {
		return "", err
	}
	dockerfile, err := os.Create(dockerfilePath)
	if err != nil {
		return "", err
	}
	defer dockerfile.Close()
	if err = t.Execute(dockerfile, struct {
		BaseImage string
		Port      string
	}{
		baseImage,
		fmt.Sprintf("%d", serverPort),
	}); err != nil {
		return "", err
	}
	return dockerfilePath, nil
}
开发者ID:danielfireman,项目名称:phd,代码行数:30,代码来源:docker.go

示例13: realMain

func realMain() int {

	// important to have GOPATH defined
	if _, ok := os.LookupEnv("GOPATH"); !ok {
		fmt.Println("Environment variabe GOPATH not found!")
		return 1
	}

	// reads config from file
	config, err := ReadConfig("./config.json")
	if err != nil {
		fmt.Println("Config file reading error. Details: ", err)
		return 2
	}

	// creates Logger (can be replaced with other popular logger)
	log := log.New(os.Stdout, "BEN ", log.Ldate|log.Ltime)
	log.Println("Application launched")

	br, err := NewBenchClient(config.AuthKey, config.Email, config.BaseUrl, log)
	if err != nil {
		log.Println("BenchRunner init failed. Details: ", err)
		return 3
	}

	// Ctrl+C grcefully terminates application
	br.Run()

	log.Println("Application succesfully terminated")
	return 0
}
开发者ID:gophergala2016,项目名称:gobench,代码行数:31,代码来源:main.go

示例14: overrideField

func (cl ConfigLoader) overrideField(sf reflect.StructField, originalVal reflect.Value) error {
	envName := sf.Tag.Get("env")
	if envName == "" {
		return nil
	}
	envVal, present := os.LookupEnv(envName)
	if !present {
		return nil
	}
	var finalVal reflect.Value
	switch originalVal.Interface().(type) {
	default:
		return fmt.Errorf("unable to override fields of type %T", originalVal.Interface())
	case string:
		finalVal = reflect.ValueOf(envVal)
	case int:
		i, err := strconv.Atoi(envVal)
		if err != nil {
			return err
		}
		finalVal = reflect.ValueOf(i)
	}
	originalVal.Set(finalVal)
	return nil
}
开发者ID:opentable,项目名称:sous,代码行数:25,代码来源:configloader.go

示例15: invalidatePipeEnvVars

// invalidatePipeEnvVars stores invalid values in the Pipe specific variables
// of the current environment and returns a function to the reset any modified
// varaibles.
//
// Example:
//
//   defer invalidatePipeEnvVars()()
//   doWork...
//
func invalidatePipeEnvVars() (restore func()) {
	type val struct {
		s  string
		ok bool
	}
	lookupEnv := func(key string) val {
		s, ok := os.LookupEnv(key)
		return val{s, ok}
	}
	envVars := map[string]val{
		"__PIPE_LOG_DIR":          lookupEnv("__PIPE_LOG_DIR"),
		"__PIPE_MACHINE_IP":       lookupEnv("__PIPE_MACHINE_IP"),
		"__PIPE_NOTIFY_HTTP":      lookupEnv("__PIPE_NOTIFY_HTTP"),
		"__PIPE_SERVICE_NAME":     lookupEnv("__PIPE_SERVICE_NAME"),
		"__PIPE_SYSLOG_HOST":      lookupEnv("__PIPE_SYSLOG_HOST"),
		"__PIPE_SYSLOG_PORT":      lookupEnv("__PIPE_SYSLOG_PORT"),
		"__PIPE_SYSLOG_TRANSPORT": lookupEnv("__PIPE_SYSLOG_TRANSPORT"),
	}
	// set empty env vars
	for k := range envVars {
		os.Setenv(k, "")
	}
	// function to reset restore environemnt
	return func() {
		for k, v := range envVars {
			if v.ok {
				os.Setenv(k, v.s)
			} else {
				os.Unsetenv(k)
			}
		}
	}
}
开发者ID:mattcui,项目名称:bosh-agent,代码行数:42,代码来源:main_test.go


注:本文中的os.LookupEnv函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。