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


Golang os.Hostname函数代码示例

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


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

示例1: CollectMetrics

// CollectMetrics collects metrics for testing
func (f *Mock) CollectMetrics(mts []plugin.PluginMetricType) ([]plugin.PluginMetricType, error) {
	for _, p := range mts {
		log.Printf("collecting %+v", p)
	}
	rand.Seed(time.Now().UTC().UnixNano())
	metrics := []plugin.PluginMetricType{}
	for i := range mts {
		if mts[i].Namespace()[2] == "*" {
			hostname, _ := os.Hostname()
			for j := 0; j < 10; j++ {
				v := fmt.Sprintf("host%d", j)
				data := randInt(65, 90)
				mt := plugin.PluginMetricType{
					Data_:      data,
					Namespace_: []string{"intel", "mock", v, "baz"},
					Source_:    hostname,
					Timestamp_: time.Now(),
					Labels_:    mts[i].Labels(),
					Version_:   mts[i].Version(),
				}
				metrics = append(metrics, mt)
			}
		} else {
			data := randInt(65, 90)
			mts[i].Data_ = data
			mts[i].Source_, _ = os.Hostname()
			mts[i].Timestamp_ = time.Now()
			metrics = append(metrics, mts[i])
		}
	}
	return metrics, nil
}
开发者ID:gitter-badger,项目名称:snap-1,代码行数:33,代码来源:mock.go

示例2: NewStorageDriver

func NewStorageDriver(driverName string) (storage.StorageDriver, error) {
	var storageDriver storage.StorageDriver
	var err error
	// TODO(vmarmol): We shouldn't need the housekeeping interval here and it shouldn't be public.
	samplesToCache := int(*argDbBufferDuration / *manager.HousekeepingInterval)
	if samplesToCache < statsRequestedByUI {
		// The UI requests the most recent 60 stats by default.
		samplesToCache = statsRequestedByUI
	}
	switch driverName {
	case "":
		// empty string by default is the in memory store
		fallthrough
	case "memory":
		storageDriver = memory.New(*argSampleSize, int(*argDbBufferDuration))
		return storageDriver, nil
	case "influxdb":
		var hostname string
		hostname, err = os.Hostname()
		if err != nil {
			return nil, err
		}

		storageDriver, err = influxdb.New(
			hostname,
			"stats",
			*argDbName,
			*argDbUsername,
			*argDbPassword,
			*argDbHost,
			*argDbIsSecure,
			*argDbBufferDuration,
			// TODO(monnand): One hour? Or user-defined?
			1*time.Hour,
		)
		glog.V(2).Infof("Caching %d recent stats in memory\n", samplesToCache)
		storageDriver = cache.MemoryCache(samplesToCache, samplesToCache, storageDriver)
	case "bigquery":
		var hostname string
		hostname, err = os.Hostname()
		if err != nil {
			return nil, err
		}
		storageDriver, err = bigquery.New(
			hostname,
			"cadvisor",
			*argDbName,
			1*time.Hour,
		)
		glog.V(2).Infof("Caching %d recent stats in memory\n", samplesToCache)
		storageDriver = cache.MemoryCache(samplesToCache, samplesToCache, storageDriver)

	default:
		err = fmt.Errorf("Unknown database driver: %v", *argDbDriver)
	}
	if err != nil {
		return nil, err
	}
	return storageDriver, nil
}
开发者ID:hmalphettes,项目名称:cadvisor,代码行数:60,代码来源:storagedriver.go

示例3: eventWorker

func eventWorker() {
	go func() {
		// a ticker channel to limit reloads to marathon, 1s is enough for now.
		ticker := time.NewTicker(1 * time.Second)
		for {
			select {
			case <-ticker.C:
				<-eventqueue
				start := time.Now()
				err := reload()
				elapsed := time.Since(start)
				if err != nil {
					log.Println("config update failed")
					if config.Statsd != "" {
						go func() {
							hostname, _ := os.Hostname()
							statsd.Counter(1.0, "nixy."+hostname+".reload.failed", 1)
						}()
					}
				} else {
					log.Printf("config update took %s\n", elapsed)
					if config.Statsd != "" {
						go func(elapsed time.Duration) {
							hostname, _ := os.Hostname()
							statsd.Counter(1.0, "nixy."+hostname+".reload.success", 1)
							statsd.Timing(1.0, "nixy."+hostname+".reload.time", elapsed)
						}(elapsed)
					}
				}
			}
		}
	}()
}
开发者ID:imjerrybao,项目名称:nixy,代码行数:33,代码来源:marathon.go

示例4: NewStorageDriver

func NewStorageDriver(driverName string) (*memory.InMemoryStorage, error) {
	var storageDriver *memory.InMemoryStorage
	var backendStorage storage.StorageDriver
	var err error
	// TODO(vmarmol): We shouldn't need the housekeeping interval here and it shouldn't be public.
	samplesToCache := int(*argDbBufferDuration / *manager.HousekeepingInterval)
	if samplesToCache < statsRequestedByUI {
		// The UI requests the most recent 60 stats by default.
		samplesToCache = statsRequestedByUI
	}
	switch driverName {
	case "":
		backendStorage = nil
	case "influxdb":
		var hostname string
		hostname, err = os.Hostname()
		if err != nil {
			return nil, err
		}

		backendStorage, err = influxdb.New(
			hostname,
			"stats",
			*argDbName,
			*argDbUsername,
			*argDbPassword,
			*argDbHost,
			*argDbIsSecure,
			*argDbBufferDuration,
			// TODO(monnand): One hour? Or user-defined?
			1*time.Hour,
		)
	case "bigquery":
		var hostname string
		hostname, err = os.Hostname()
		if err != nil {
			return nil, err
		}
		backendStorage, err = bigquery.New(
			hostname,
			"cadvisor",
			*argDbName,
			1*time.Hour,
		)

	default:
		err = fmt.Errorf("Unknown database driver: %v", *argDbDriver)
	}
	if err != nil {
		return nil, err
	}
	glog.Infof("Caching %d recent stats in memory; using \"%v\" storage driver\n", samplesToCache, driverName)
	storageDriver = memory.New(samplesToCache, samplesToCache, backendStorage)
	return storageDriver, nil
}
开发者ID:cnf,项目名称:cadvisor,代码行数:55,代码来源:storagedriver.go

示例5: main

func main() {
	http.HandleFunc("/zk", getNodeInfo)
	os.Hostname()
	hostName, err := os.Hostname()
	if err != nil {
		panic(err)
	}
	errr := http.ListenAndServe(hostName+":"+config.HttpPort, nil)
	if errr != nil {
		panic(errr)
	}
}
开发者ID:kevin8096,项目名称:go-zk,代码行数:12,代码来源:ZkClient.go

示例6: main

func main() {
	c.Hostname, _ = os.Hostname()
	for _, e := range os.Environ() {
		pair := strings.Split(e, "=")
		c.Env = append(c.Env, EnvVar{pair[0], pair[1]})
	}
	fmt.Println(c)
	static := web.New()
	static.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.Handle("/static/", static)

	goji.Get("/", renderIndex)

	// Setup our service export
	host, _ := os.Hostname()
	info := []string{"simple peer discovery test"}
	service, _ := mdns.NewMDNSService(host, "_http._tcp", "", "", 8000, nil, info)

	// Create the mDNS server, defer shutdown
	fmt.Println("Creating mDNS server")
	server, _ := mdns.NewServer(&mdns.Config{Zone: service})
	defer server.Shutdown()

	// Make a channel for results and start listening
	peers := make(chan *mdns.ServiceEntry, 4)
	go func() {
		fmt.Println("Waiting for peers")
		for entry := range peers {
			known := false
			for _, e := range c.Peers {
				if entry.Name == e {
					known = true
				}
			}
			if known == false {
				fmt.Println("Got new peer", entry.Name)
				c.Peers = append(c.Peers, entry.Name)
			}
		}
	}()

	fmt.Println("Creating mDNS listener")
	//mdns.Lookup("_googlecast._tcp", peers)

	// this will panic without IF_MULTICAST, causing the program to exit
	mdns.Lookup("_http._tcp", peers)

	fmt.Println("Creating HTTP server")
	goji.Serve() // port 8000 by default
	close(peers)
}
开发者ID:ruo91,项目名称:go-http-mdns,代码行数:51,代码来源:web.go

示例7: NewFileLogger

func NewFileLogger(gzipEnabled bool, compressionLevel int, filenameFormat, topic string) (*FileLogger, error) {
	if gzipEnabled && strings.Index(filenameFormat, "<GZIPREV>") == -1 {
		return nil, errors.New("missing <GZIPREV> in filenameFormat")
	}

	hostname, err := os.Hostname()
	if err != nil {
		return nil, err
	}
	shortHostname := strings.Split(hostname, ".")[0]
	identifier := shortHostname
	if len(*hostIdentifier) != 0 {
		identifier = strings.Replace(*hostIdentifier, "<SHORT_HOST>", shortHostname, -1)
		identifier = strings.Replace(identifier, "<HOSTNAME>", hostname, -1)
	}
	filenameFormat = strings.Replace(filenameFormat, "<TOPIC>", topic, -1)
	filenameFormat = strings.Replace(filenameFormat, "<HOST>", identifier, -1)
	if gzipEnabled && !strings.HasSuffix(filenameFormat, ".gz") {
		filenameFormat = filenameFormat + ".gz"
	}

	f := &FileLogger{
		logChan:          make(chan *Message, 1),
		compressionLevel: compressionLevel,
		filenameFormat:   filenameFormat,
		gzipEnabled:      gzipEnabled,
		ExitChan:         make(chan int),
		termChan:         make(chan bool),
		hupChan:          make(chan bool),
	}
	return f, nil
}
开发者ID:Thoughting,项目名称:nsq,代码行数:32,代码来源:nsq_to_file.go

示例8: authTokenNote

func authTokenNote(num int) (string, error) {
	n := os.Getenv("USER")

	if n == "" {
		n = os.Getenv("USERNAME")
	}

	if n == "" {
		whoami := exec.Command("whoami")
		whoamiOut, err := whoami.Output()
		if err != nil {
			return "", err
		}
		n = strings.TrimSpace(string(whoamiOut))
	}

	h, err := os.Hostname()
	if err != nil {
		return "", err
	}

	if num > 1 {
		return fmt.Sprintf("hub for %[email protected]%s %d", n, h, num), nil
	}

	return fmt.Sprintf("hub for %[email protected]%s", n, h), nil
}
开发者ID:aergonaut,项目名称:hub,代码行数:27,代码来源:client.go

示例9: buildHost

func buildHost() string {
	h, err := os.Hostname()
	if err != nil {
		return "unknown-host"
	}
	return h
}
开发者ID:WeavingCode,项目名称:syncthing,代码行数:7,代码来源:build.go

示例10: startMetrics

func startMetrics(appName, graphiteServer string) {
	if graphiteServer == "" {
		glog.Warningf("No metrics server specified.")
		return
	}

	addr, err := net.ResolveTCPAddr("tcp", graphiteServer)
	if err != nil {
		glog.Fatalf("Unable to resolve metrics server address: %s", err)
	}

	// Get the hostname and create the app-prefix.
	hostName, err := os.Hostname()
	if err != nil {
		glog.Fatalf("Unable to retrieve hostname: %s", err)
	}
	appPrefix := fmt.Sprintf("%s.%s", appName, strings.Replace(hostName, ".", "-", -1))

	// Runtime metrics.
	metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry)
	go metrics.CaptureRuntimeMemStats(metrics.DefaultRegistry, SAMPLE_PERIOD)
	go graphite.Graphite(metrics.DefaultRegistry, SAMPLE_PERIOD, appPrefix, addr)

	// Uptime.
	uptimeGuage := metrics.GetOrRegisterGaugeFloat64("uptime", metrics.DefaultRegistry)
	go func() {
		startTime := time.Now()
		uptimeGuage.Update(0)
		for _ = range time.Tick(SAMPLE_PERIOD) {
			uptimeGuage.Update(time.Since(startTime).Seconds())
		}
	}()
}
开发者ID:Tiger66639,项目名称:skia-buildbot,代码行数:33,代码来源:common.go

示例11: init

func init() {
	// Set up builtin middlewarez
	OnBeforeNotify(httpRequestMiddleware)

	// Default configuration
	Config.update(&Configuration{
		APIKey:        "",
		Endpoint:      "https://notify.bugsnag.com/",
		Hostname:      "",
		AppVersion:    "",
		ReleaseStage:  "",
		ParamsFilters: []string{"password", "secret"},
		// * for app-engine
		ProjectPackages:     []string{"main*"},
		NotifyReleaseStages: nil,
		Logger:              log.New(os.Stdout, log.Prefix(), log.Flags()),
		PanicHandler:        defaultPanicHandler,
		Transport:           http.DefaultTransport,
	})

	hostname, err := os.Hostname()
	if err == nil {
		Config.Hostname = hostname
	}
}
开发者ID:MerlinDMC,项目名称:machine,代码行数:25,代码来源:bugsnag.go

示例12: getHostname

func getHostname() string {
	hostname, err := os.Hostname()
	if err != nil {
		hostname = "hostname"
	}
	return hostname
}
开发者ID:ninetian,项目名称:mirrorbits,代码行数:7,代码来源:utils.go

示例13: InitConfig

func InitConfig() {
	var err error

	WorkDir, err = com.WorkDir()
	if err != nil {
		panic(err)
	}

	ConfigPath = path.Join(WorkDir, "conf")

	Hostname, err := os.Hostname()
	if err != nil {
		panic(err)
	}

	fmt.Println(Hostname)

	err = initHosts()
	if err != nil {
		panic(err)
	}

	fmt.Println(Cfg)

	UserPath = path.Join(ConfigPath, Cfg.GetUserDir(Hostname))

	fmt.Println(ConfigPath, UserPath)

	InitServices()
}
开发者ID:weisd,项目名称:api,代码行数:30,代码来源:setting.go

示例14: Handle

func (*hostnameHandler) Handle(ctx context.Context, prev <-chan ql.Line, next chan<- ql.Line, config map[string]interface{}) error {

	field := "hostname"
	ok := true

	fieldIface := config["field"]
	if fieldIface != nil {
		field, ok = fieldIface.(string)
		if !ok {
			log.Log(ctx).Warn("Could not parse hostname config, using field=hostname")
			field = "hostname"
		}
	}

	log.Log(ctx).Debug("Starting filter handler", "handler", "hostname", "field", field)

	hostname, _ := os.Hostname()

	go func() {
		for {
			select {
			case line := <-prev:
				line.Data[field] = hostname
				next <- line
			case <-ctx.Done():
				return
			}
		}
	}()

	return nil
}
开发者ID:sheenobu,项目名称:quicklog,代码行数:32,代码来源:hostname.go

示例15: prepare

func (cfg *Configuration) prepare(myID protocol.DeviceID) error {
	var myName string

	// Ensure this device is present in the config
	for _, device := range cfg.Devices {
		if device.DeviceID == myID {
			goto found
		}
	}

	myName, _ = os.Hostname()
	cfg.Devices = append(cfg.Devices, DeviceConfiguration{
		DeviceID: myID,
		Name:     myName,
	})

found:

	if err := cfg.clean(); err != nil {
		return err
	}

	// Ensure that we are part of the devices
	for i := range cfg.Folders {
		cfg.Folders[i].Devices = ensureDevicePresent(cfg.Folders[i].Devices, myID)
	}

	return nil
}
开发者ID:kluppy,项目名称:syncthing,代码行数:29,代码来源:config.go


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