本文整理汇总了Golang中github.com/pivotal-golang/localip.LocalIP函数的典型用法代码示例。如果您正苦于以下问题:Golang LocalIP函数的具体用法?Golang LocalIP怎么用?Golang LocalIP使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了LocalIP函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: initializeServer
func initializeServer(
bbsClient bbs.Client,
executorClient executor.Client,
evacuatable evacuation_context.Evacuatable,
evacuationReporter evacuation_context.EvacuationReporter,
logger lager.Logger,
stackMap rep.StackPathMap,
supportedProviders []string,
) (ifrit.Runner, string) {
lrpStopper := initializeLRPStopper(*cellID, executorClient, logger)
auctionCellRep := auction_cell_rep.New(*cellID, stackMap, supportedProviders, *zone, generateGuid, executorClient, evacuationReporter, logger)
handlers := handlers.New(auctionCellRep, lrpStopper, executorClient, evacuatable, logger)
router, err := rata.NewRouter(rep.Routes, handlers)
if err != nil {
logger.Fatal("failed-to-construct-router", err)
}
ip, err := localip.LocalIP()
if err != nil {
logger.Fatal("failed-to-fetch-ip", err)
}
port := strings.Split(*listenAddr, ":")[1]
address := fmt.Sprintf("http://%s:%s", ip, port)
return http_server.New(*listenAddr, router), address
}
开发者ID:stefanschneider,项目名称:rep,代码行数:29,代码来源:main.go
示例2: initializeServerRegistration
func initializeServerRegistration(logger lager.Logger) (registration natbeat.RegistryMessage) {
domains := strings.Split(*serverDomainNames, ",")
addressComponents := strings.Split(*serverAddress, ":")
if len(addressComponents) != 2 {
logger.Error("server-address-invalid", fmt.Errorf("%s is not a valid serverAddress", *serverAddress))
os.Exit(1)
}
host, err := localip.LocalIP()
if err != nil {
logger.Error("local-ip-invalid", err)
os.Exit(1)
}
port, err := strconv.Atoi(addressComponents[1])
if err != nil {
logger.Error("server-address-invalid", fmt.Errorf("%s does not have a valid port", *serverAddress))
os.Exit(1)
}
return natbeat.RegistryMessage{
URIs: domains,
Host: host,
Port: port,
}
}
开发者ID:rajkumargithub,项目名称:lattice,代码行数:27,代码来源:main.go
示例3: AddWSSink
func AddWSSink(receivedChan chan []byte, port string, path string) (*websocket.Conn, <-chan struct{}) {
connectionDroppedChannel := make(chan struct{}, 1)
var ws *websocket.Conn
ip, _ := localip.LocalIP()
fullURL := "ws://" + ip + ":" + port + path
Eventually(func() error {
var err error
ws, _, err = websocket.DefaultDialer.Dial(fullURL, http.Header{})
return err
}, 5, 1).ShouldNot(HaveOccurred(), fmt.Sprintf("Unable to connect to server at %s.", fullURL))
ws.SetPingHandler(func(message string) error {
ws.WriteControl(websocket.PongMessage, []byte(message), time.Time{})
return nil
})
go func() {
for {
_, data, err := ws.ReadMessage()
if err != nil {
close(connectionDroppedChannel)
close(receivedChan)
return
}
receivedChan <- data
}
}()
return ws, connectionDroppedChannel
}
开发者ID:rakutentech,项目名称:loggregator,代码行数:35,代码来源:helpers.go
示例4: main
func main() {
// Metron is intended to be light-weight so we occupy only one core
runtime.GOMAXPROCS(1)
flag.Parse()
config, err := config.ParseConfig(*configFilePath)
if err != nil {
panic(fmt.Errorf("Unable to parse config: %s", err))
}
localIp, err := localip.LocalIP()
if err != nil {
panic(fmt.Errorf("Unable to resolve own IP address: %s", err))
}
log := logger.NewLogger(*debug, *logFilePath, "metron", config.Syslog)
go func() {
err := http.ListenAndServe(net.JoinHostPort(localIp, pprofPort), nil)
if err != nil {
log.Errorf("Error starting pprof server: %s", err.Error())
}
}()
log.Info("Startup: Setting up the Metron agent")
marshaller, err := initializeDopplerPool(config, log)
if err != nil {
panic(fmt.Errorf("Could not initialize doppler connection pool: %s", err))
}
messageTagger := tagger.New(config.Deployment, config.Job, config.Index, marshaller)
aggregator := messageaggregator.New(messageTagger, log)
statsStopChan := make(chan struct{})
initializeMetrics(messageTagger, config, statsStopChan, log)
dropsondeUnmarshaller := eventunmarshaller.New(aggregator, log)
metronAddress := fmt.Sprintf("127.0.0.1:%d", config.IncomingUDPPort)
dropsondeReader, err := networkreader.New(metronAddress, "dropsondeAgentListener", dropsondeUnmarshaller, log)
if err != nil {
panic(fmt.Errorf("Failed to listen on %s: %s", metronAddress, err))
}
log.Info("metron started")
go dropsondeReader.Start()
dumpChan := signalmanager.RegisterGoRoutineDumpSignalChannel()
killChan := signalmanager.RegisterKillSignalChannel()
for {
select {
case <-dumpChan:
signalmanager.DumpGoRoutine()
case <-killChan:
log.Info("Shutting down")
close(statsStopChan)
return
}
}
}
开发者ID:yingkitw,项目名称:loggregator,代码行数:59,代码来源:main.go
示例5: createClient
func (d *DatadogFirehoseNozzle) createClient() {
ipAddress, err := localip.LocalIP()
if err != nil {
panic(err)
}
d.client = datadogclient.New(d.config.DataDogURL, d.config.DataDogAPIKey, d.config.MetricPrefix, d.config.Deployment, ipAddress)
}
开发者ID:daverc1-pivotal,项目名称:datadog-firehose-nozzle,代码行数:8,代码来源:datadog_firehose_nozzle.go
示例6: initiateFirehoseConnection
func initiateFirehoseConnection() (*noaa.Consumer, chan *events.Envelope) {
localIP, _ := localip.LocalIP()
firehoseConnection := noaa.NewConsumer("ws://"+localIP+":49629", &tls.Config{InsecureSkipVerify: true}, nil)
msgChan := make(chan *events.Envelope, 2000)
errorChan := make(chan error)
go firehoseConnection.Firehose("uniqueId", "", msgChan, errorChan)
return firehoseConnection, msgChan
}
开发者ID:hpcloud,项目名称:loggregator-1,代码行数:8,代码来源:firehose_reader.go
示例7: main
func main() {
flag.Parse()
config, logger, err := config.ParseConfig(logLevel, configFile, logFilePath)
if err != nil {
panic(err)
}
profiler := profiler.NewProfiler(*cpuprofile, *memprofile, 1*time.Second, logger)
profiler.Profile()
defer profiler.Stop()
uptimeMonitor := monitor.NewUptimeMonitor(time.Duration(config.MonitorIntervalSeconds) * time.Second)
go uptimeMonitor.Start()
defer uptimeMonitor.Stop()
dropsonde.Initialize("localhost:"+strconv.Itoa(config.MetronPort), "LoggregatorTrafficController")
adapter := DefaultStoreAdapterProvider(config.EtcdUrls, config.EtcdMaxConcurrentRequests)
adapter.Connect()
ipAddress, err := localip.LocalIP()
if err != nil {
panic(err)
}
dopplerProxy := makeDopplerProxy(adapter, config, logger)
startOutgoingDopplerProxy(net.JoinHostPort(ipAddress, strconv.FormatUint(uint64(config.OutgoingDropsondePort), 10)), dopplerProxy)
legacyProxy := makeLegacyProxy(adapter, config, logger)
startOutgoingProxy(net.JoinHostPort(ipAddress, strconv.FormatUint(uint64(config.OutgoingPort), 10)), legacyProxy)
rr := routerregistrar.NewRouterRegistrar(config.MbusClient, logger)
uri := "loggregator." + config.SystemDomain
err = rr.RegisterWithRouter(ipAddress, config.OutgoingPort, []string{uri})
if err != nil {
logger.Fatalf("Startup: Did not get response from router when greeting. Using default keep-alive for now. Err: %v.", err)
}
uri = "doppler." + config.SystemDomain
err = rr.RegisterWithRouter(ipAddress, config.OutgoingDropsondePort, []string{uri})
if err != nil {
logger.Fatalf("Startup: Did not get response from router when greeting. Using default keep-alive for now. Err: %v.", err)
}
killChan := make(chan os.Signal)
signal.Notify(killChan, os.Kill, os.Interrupt)
for {
select {
case <-cfcomponent.RegisterGoRoutineDumpSignalChannel():
cfcomponent.DumpGoRoutine()
case <-killChan:
rr.UnregisterFromRouter(ipAddress, config.OutgoingPort, []string{uri})
break
}
}
}
开发者ID:rakutentech,项目名称:loggregator,代码行数:58,代码来源:main.go
示例8: createClient
func (d *InfluxDbFirehoseNozzle) createClient() {
ipAddress, err := localip.LocalIP()
if err != nil {
panic(err)
}
d.client = influxdbclient.New(d.config.InfluxDbUrl, d.config.InfluxDbDatabase, d.config.InfluxDbUser,
d.config.InfluxDbPassword, d.config.MetricPrefix, d.config.Deployment, ipAddress)
}
开发者ID:roxtar,项目名称:influxdb-firehose-nozzle,代码行数:9,代码来源:influxdb_firehose_nozzle.go
示例9: New
func New(deploymentName string, job string, index uint, outputWriter writers.EnvelopeWriter) *Tagger {
ip, _ := localip.LocalIP()
return &Tagger{
deploymentName: deploymentName,
job: job,
index: strconv.Itoa(int(index)),
ip: ip,
outputWriter: outputWriter,
}
}
开发者ID:lyuyun,项目名称:loggregator,代码行数:10,代码来源:tagger.go
示例10: basicTaggedHttpStartStopMessage
func basicTaggedHttpStartStopMessage(envelope events.Envelope) *events.Envelope {
ip, _ := localip.LocalIP()
envelope.Deployment = proto.String("test-deployment")
envelope.Job = proto.String("test-job")
envelope.Index = proto.String("2")
envelope.Ip = proto.String(ip)
return &envelope
}
开发者ID:khj0651,项目名称:loggregator,代码行数:10,代码来源:tagger_test.go
示例11: Start
func (c *VcapComponent) Start() error {
if c.Type == "" {
log.Error("Component type is required")
return errors.New("type is required")
}
c.quitCh = make(chan struct{}, 1)
c.StartTime = Time(time.Now())
uuid, err := GenerateUUID()
if err != nil {
return err
}
c.UUID = fmt.Sprintf("%d-%s", c.Index, uuid)
if c.Host == "" {
host, err := localip.LocalIP()
if err != nil {
log.Error(err.Error())
return err
}
port, err := localip.LocalPort()
if err != nil {
log.Error(err.Error())
return err
}
c.Host = fmt.Sprintf("%s:%d", host, port)
}
if c.Credentials == nil || len(c.Credentials) != 2 {
user, err := GenerateUUID()
if err != nil {
return err
}
password, err := GenerateUUID()
if err != nil {
return err
}
c.Credentials = []string{user, password}
}
if c.Logger != nil {
log = c.Logger
}
c.Varz.NumCores = runtime.NumCPU()
c.Varz.component = *c
procStat = NewProcessStatus()
c.ListenAndServe()
return nil
}
开发者ID:jungle0755,项目名称:gorouter,代码行数:55,代码来源:component.go
示例12: NewDiegoExecutor
func NewDiegoExecutor() *DiegoExecutor {
ip, _ := localip.LocalIP()
address := fmt.Sprintf("http://%s:%v", ip, 1800)
repClientFactory := rep.NewClientFactory(cf_http.NewClient())
cellClient := repClientFactory.CreateClient(address)
return &DiegoExecutor{
cellClient: cellClient,
taskStateMap: map[string]mesos.TaskState{},
}
}
开发者ID:LaynePeng,项目名称:cloudfoundry-mesos,代码行数:11,代码来源:executor.go
示例13: defaultExternalIP
func defaultExternalIP(ip IPFlag) (net.IP, error) {
if ip != nil {
return ip.IP(), nil
}
localIP, err := localip.LocalIP()
if err != nil {
return nil, fmt.Errorf("Couldn't determine local IP to use for --external-ip parameter. You can use the --external-ip flag to pass an external IP explicitly.")
}
return net.ParseIP(localIP), nil
}
开发者ID:cloudfoundry,项目名称:guardian,代码行数:12,代码来源:command.go
示例14: main
func main() {
flag.Parse()
config, err := config.ParseConfig(*logLevel, *configFile, *logFilePath)
if err != nil {
panic(err)
}
log := logger.NewLogger(*logLevel, *logFilePath, "loggregator trafficcontroller", config.Syslog)
log.Info("Startup: Setting up the loggregator traffic controller")
dropsonde.Initialize("localhost:"+strconv.Itoa(config.MetronPort), "LoggregatorTrafficController")
profiler := profiler.NewProfiler(*cpuprofile, *memprofile, 1*time.Second, log)
profiler.Profile()
defer profiler.Stop()
uptimeMonitor := monitor.NewUptimeMonitor(time.Duration(config.MonitorIntervalSeconds) * time.Second)
go uptimeMonitor.Start()
defer uptimeMonitor.Stop()
dopplerAdapter := DefaultStoreAdapterProvider(config.EtcdUrls, config.EtcdMaxConcurrentRequests)
dopplerAdapter.Connect()
legacyAdapter := DefaultStoreAdapterProvider(config.EtcdUrls, config.EtcdMaxConcurrentRequests)
legacyAdapter.Connect()
ipAddress, err := localip.LocalIP()
if err != nil {
panic(err)
}
dopplerProxy := makeDopplerProxy(dopplerAdapter, config, log)
startOutgoingDopplerProxy(net.JoinHostPort(ipAddress, strconv.FormatUint(uint64(config.OutgoingDropsondePort), 10)), dopplerProxy)
legacyProxy := makeLegacyProxy(legacyAdapter, config, log)
startOutgoingProxy(net.JoinHostPort(ipAddress, strconv.FormatUint(uint64(config.OutgoingPort), 10)), legacyProxy)
killChan := make(chan os.Signal)
signal.Notify(killChan, os.Kill, os.Interrupt)
dumpChan := registerGoRoutineDumpSignalChannel()
for {
select {
case <-dumpChan:
logger.DumpGoRoutine()
case <-killChan:
break
}
}
}
开发者ID:pkdevbox,项目名称:loggregator,代码行数:52,代码来源:main.go
示例15: createClient
func (o *OpenTSDBFirehoseNozzle) createClient() {
ipAddress, err := localip.LocalIP()
if err != nil {
panic(err)
}
var transporter opentsdbclient.Poster
if o.config.UseTelnetAPI {
transporter = poster.NewTelnetPoster(o.config.OpenTSDBURL)
} else {
transporter = poster.NewHTTPPoster(o.config.OpenTSDBURL)
}
o.client = opentsdbclient.New(transporter, o.config.MetricPrefix, o.config.Deployment, o.config.Job, o.config.Index, ipAddress)
}
开发者ID:pivotal-cf-experimental,项目名称:opentsdb-firehose-nozzle,代码行数:14,代码来源:opentsdb_firehose_nozzle.go
示例16: Process
func (c *Config) Process() {
var err error
if c.GoMaxProcs == -1 {
c.GoMaxProcs = runtime.NumCPU()
}
c.PruneStaleDropletsInterval = time.Duration(c.PruneStaleDropletsIntervalInSeconds) * time.Second
c.DropletStaleThreshold = time.Duration(c.DropletStaleThresholdInSeconds) * time.Second
c.PublishActiveAppsInterval = time.Duration(c.PublishActiveAppsIntervalInSeconds) * time.Second
c.StartResponseDelayInterval = time.Duration(c.StartResponseDelayIntervalInSeconds) * time.Second
c.EndpointTimeout = time.Duration(c.EndpointTimeoutInSeconds) * time.Second
c.RouteServiceTimeout = time.Duration(c.RouteServiceTimeoutInSeconds) * time.Second
c.Logging.JobName = "router_" + c.Zone + "_" + strconv.Itoa(int(c.Index))
if c.StartResponseDelayInterval > c.DropletStaleThreshold {
c.DropletStaleThreshold = c.StartResponseDelayInterval
log := steno.NewLogger("config.logger")
log.Warnf("DropletStaleThreshold (%s) cannot be less than StartResponseDelayInterval (%s); setting both equal to StartResponseDelayInterval and continuing", c.DropletStaleThreshold, c.StartResponseDelayInterval)
}
drain := c.DrainTimeoutInSeconds
if drain == 0 {
drain = c.EndpointTimeoutInSeconds
}
c.DrainTimeout = time.Duration(drain) * time.Second
c.Ip, err = localip.LocalIP()
if err != nil {
panic(err)
}
if c.EnableSSL {
c.CipherSuites = c.processCipherSuites()
cert, err := tls.LoadX509KeyPair(c.SSLCertPath, c.SSLKeyPath)
if err != nil {
panic(err)
}
c.SSLCertificate = cert
}
if c.RouteServiceSecrets != nil && len(c.RouteServiceSecrets) > 0 {
c.RouteServiceEnabled = true
c.RouteServiceSecret = c.RouteServiceSecrets[0]
if len(c.RouteServiceSecrets) > 1 {
c.RouteServiceSecretPrev = c.RouteServiceSecrets[1]
}
}
}
开发者ID:caseyhadden,项目名称:gorouter,代码行数:50,代码来源:config.go
示例17: greetMessage
func (r *Router) greetMessage() ([]byte, error) {
host, err := localip.LocalIP()
if err != nil {
return nil, err
}
d := vcap.RouterStart{
Id: r.component.UUID,
Hosts: []string{host},
MinimumRegisterIntervalInSeconds: r.config.StartResponseDelayIntervalInSeconds,
PruneThresholdInSeconds: r.config.DropletStaleThresholdInSeconds,
}
return json.Marshal(d)
}
开发者ID:trainchou,项目名称:gorouter,代码行数:15,代码来源:router.go
示例18: parseExternalIP
func parseExternalIP(ip string) (net.IP, error) {
if *externalIP == "" {
localIP, err := localip.LocalIP()
if err != nil {
return nil, fmt.Errorf("Couldn't determine local IP to use for -externalIP parameter. You can use the -externalIP flag to pass an external IP")
}
externalIP = &localIP
}
externalIPAddr := net.ParseIP(*externalIP)
if externalIPAddr == nil {
return nil, fmt.Errorf("Value of -externalIP %s could not be converted to an IP", *externalIP)
}
return externalIPAddr, nil
}
开发者ID:digideskio,项目名称:guardian,代码行数:15,代码来源:main.go
示例19: Process
func (c *Config) Process() {
var err error
if c.GoMaxProcs == -1 {
c.GoMaxProcs = runtime.NumCPU()
}
c.PruneStaleDropletsInterval = time.Duration(c.PruneStaleDropletsIntervalInSeconds) * time.Second
c.DropletStaleThreshold = time.Duration(c.DropletStaleThresholdInSeconds) * time.Second
c.PublishActiveAppsInterval = time.Duration(c.PublishActiveAppsIntervalInSeconds) * time.Second
c.StartResponseDelayInterval = time.Duration(c.StartResponseDelayIntervalInSeconds) * time.Second
c.EndpointTimeout = time.Duration(c.EndpointTimeoutInSeconds) * time.Second
c.RouteServiceTimeout = time.Duration(c.RouteServiceTimeoutInSeconds) * time.Second
c.TokenFetcherRetryInterval = time.Duration(c.TokenFetcherRetryIntervalInSeconds) * time.Second
c.Logging.JobName = "gorouter"
if c.StartResponseDelayInterval > c.DropletStaleThreshold {
c.DropletStaleThreshold = c.StartResponseDelayInterval
c.logger.Info(fmt.Sprintf("DropletStaleThreshold (%s) cannot be less than StartResponseDelayInterval (%s); setting both equal to StartResponseDelayInterval and continuing", c.DropletStaleThreshold, c.StartResponseDelayInterval))
}
c.DrainTimeout = c.EndpointTimeout
if c.DrainTimeoutInSeconds > 0 {
c.DrainTimeout = time.Duration(c.DrainTimeoutInSeconds) * time.Second
}
if c.DrainWaitInSeconds > 0 {
c.DrainWait = time.Duration(c.DrainWaitInSeconds) * time.Second
}
c.Ip, err = localip.LocalIP()
if err != nil {
panic(err)
}
if c.EnableSSL {
c.CipherSuites = c.processCipherSuites()
cert, err := tls.LoadX509KeyPair(c.SSLCertPath, c.SSLKeyPath)
if err != nil {
panic(err)
}
c.SSLCertificate = cert
}
if c.RouteServiceSecret != "" {
c.RouteServiceEnabled = true
}
}
开发者ID:shashankmjain,项目名称:gorouter,代码行数:47,代码来源:config.go
示例20: main
func main() {
runtime.GOMAXPROCS(4)
var interval = flag.String("interval", "1s", "Interval for reported results")
var writeRate = flag.Int("writeRate", 15000, "Number of writes per second to send to doppler")
var stopAfter = flag.String("stopAfter", "5m", "How long to run the experiment for")
var sharedSecret string
flag.StringVar(&sharedSecret, "sharedSecret", "", "Shared secret used by Doppler to verify message validity")
var dopplerOutgoingPort = flag.Int("dopplerOutgoingPort", 8080, "Outgoing port from doppler")
var dopplerIncomingDropsondePort = flag.Int("dopplerIncomingDropsondePort", 3457, "Incoming dropsonde port to doppler")
flag.Parse()
duration, err := time.ParseDuration(*interval)
if err != nil {
log.Fatalf("Invalid duration %s\n", *interval)
}
stopAfterDuration, err := time.ParseDuration(*stopAfter)
if err != nil {
log.Fatalf("Invalid duration %s\n", *stopAfter)
}
reporter := metricsreporter.New(duration, os.Stdout)
ip, err := localip.LocalIP()
if err != nil {
panic(err)
}
generator := messagegenerator.NewValueMetricGenerator()
writer := messagewriter.NewMessageWriter(ip, *dopplerIncomingDropsondePort, sharedSecret, reporter.GetSentCounter())
reader := websocketmessagereader.New(fmt.Sprintf("%s:%d", ip, *dopplerOutgoingPort), reporter.GetReceivedCounter())
defer reader.Close()
writeStrategy := writestrategies.NewConstantWriteStrategy(generator, writer, *writeRate)
exp := experiment.NewExperiment(reader)
exp.AddWriteStrategy(writeStrategy)
go reporter.Start()
go exp.Start()
timer := time.NewTimer(stopAfterDuration)
<-timer.C
exp.Stop()
reporter.Stop()
}
开发者ID:rakutentech,项目名称:loggregator,代码行数:46,代码来源:main.go
注:本文中的github.com/pivotal-golang/localip.LocalIP函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论