Golang JoinHostPort示例

说明

golang joinhostport示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net

示例#1
文件: docker_registry_service.go 项目: Xmagicer/origin

// getDockerRegistryLocations returns the dns form and the ip form of the secret
func (e *DockerRegistryServiceController) getDockerRegistryLocations() []string {
	key, err := controller.KeyFunc(&kapi.Service{ObjectMeta: kapi.ObjectMeta{Name: e.serviceName, Namespace: e.serviceNamespace}})
	if err != nil {
		return []string{}
	}

	obj, exists, err := e.serviceCache.GetByKey(key)
	if err != nil {
		return []string{}
	}
	if !exists {
		return []string{}
	}
	service := obj.(*kapi.Service)

	hasPortalIP := (len(service.Spec.ClusterIP) > 0) && (net.ParseIP(service.Spec.ClusterIP) != nil)
	if hasPortalIP && len(service.Spec.Ports) > 0 {
		return []string{
			net.JoinHostPort(service.Spec.ClusterIP, fmt.Sprintf("%d", service.Spec.Ports[0].Port)),
			net.JoinHostPort(fmt.Sprintf("%s.%s.svc", service.Name, service.Namespace), fmt.Sprintf("%d", service.Spec.Ports[0].Port)),
		}
	}

	return []string{}
}

示例#2
文件: proxysocket.go 项目: johndmulhausen/kubernetes

func newProxySocket(protocol api.Protocol, ip net.IP, port int) (proxySocket, error) {
	host := ""
	if ip != nil {
		host = ip.String()
	}

	switch strings.ToUpper(string(protocol)) {
	case "TCP":
		listener, err := net.Listen("tcp", net.JoinHostPort(host, strconv.Itoa(port)))
		if err != nil {
			return nil, err
		}
		return &tcpProxySocket{Listener: listener, port: port}, nil
	case "UDP":
		addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(host, strconv.Itoa(port)))
		if err != nil {
			return nil, err
		}
		conn, err := net.ListenUDP("udp", addr)
		if err != nil {
			return nil, err
		}
		return &udpProxySocket{UDPConn: conn, port: port}, nil
	}
	return nil, fmt.Errorf("unknown protocol %q", protocol)
}

示例#3
文件: main.go 项目: jordan2175/-stdyng

func main() {
	flag.Parse()

	c, err := net.ListenPacket("udp", net.JoinHostPort(*group, "0"))
	if err != nil {
		log.Fatal(err)
	}
	p := ipv4.NewPacketConn(c)
	defer p.Close()
	dst, err := net.ResolveUDPAddr("udp", net.JoinHostPort(*group, *port))
	if err != nil {
		log.Fatal(err)
	}

	log.Println(c.LocalAddr())
	go sender(p, dst)

	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	for {
		select {
		case <-sig:
			os.Exit(0)
		}
	}
}

示例#4
文件: scan_common.go 项目: kisom/cfssl

// RunScans iterates over AllScans, running each scan that matches the family
// and scanner regular expressions concurrently.
func (fs FamilySet) RunScans(host, ip, family, scanner string, timeout time.Duration) (map[string]FamilyResult, error) {
	hostname, port, err := net.SplitHostPort(host)
	if err != nil {
		hostname = host
		port = "443"
	}

	var addr string
	if net.ParseIP(ip) != nil {
		addr = net.JoinHostPort(ip, port)
	} else {
		addr = net.JoinHostPort(hostname, port)
	}

	familyRegexp, err := regexp.Compile(family)
	if err != nil {
		return nil, err
	}

	scannerRegexp, err := regexp.Compile(scanner)
	if err != nil {
		return nil, err
	}

	ctx := newContext(addr, hostname, familyRegexp, scannerRegexp, len(fs))
	for familyName, family := range fs {
		familyCtx := ctx.newfamilyContext(len(family.Scanners))
		for scannerName, scanner := range family.Scanners {
			go familyCtx.runScanner(familyName, scannerName, scanner)
		}
	}

	return ctx.copyResults(timeout), nil
}

示例#5
文件: server_run_options.go 项目: paralin/kubernetes

// Returns a clientconfig which can be used to talk to this apiserver.
func (s *ServerRunOptions) NewSelfClientConfig(token string) (*restclient.Config, error) {
	clientConfig := &restclient.Config{
		// Increase QPS limits. The client is currently passed to all admission plugins,
		// and those can be throttled in case of higher load on apiserver - see #22340 and #22422
		// for more details. Once #22422 is fixed, we may want to remove it.
		QPS:   50,
		Burst: 100,
	}

	// Use secure port if the TLSCAFile is specified
	if s.SecurePort > 0 && len(s.TLSCAFile) > 0 {
		host := s.BindAddress.String()
		if host == "0.0.0.0" {
			host = "localhost"
		}
		clientConfig.Host = "https://" + net.JoinHostPort(host, strconv.Itoa(s.SecurePort))
		clientConfig.CAFile = s.TLSCAFile
		clientConfig.BearerToken = token
	} else if s.InsecurePort > 0 {
		clientConfig.Host = net.JoinHostPort(s.InsecureBindAddress.String(), strconv.Itoa(s.InsecurePort))
	} else {
		return nil, errors.New("Unable to set url for apiserver local client")
	}

	return clientConfig, nil
}

示例#6
文件: master.go 项目: cjnygard/origin

// InstallSwaggerAPI installs the /swaggerapi/ endpoint to allow schema discovery
// and traversal.  It is optional to allow consumers of the Kubernetes master to
// register their own web services into the Kubernetes mux prior to initialization
// of swagger, so that other resource types show up in the documentation.
func (m *Master) InstallSwaggerAPI() {
	hostAndPort := m.externalHost
	protocol := "https://"

	// TODO: this is kind of messed up, we should just pipe in the full URL from the outside, rather
	// than guessing at it.
	if len(m.externalHost) == 0 && m.clusterIP != nil {
		host := m.clusterIP.String()
		if m.publicReadWritePort != 0 {
			hostAndPort = net.JoinHostPort(host, strconv.Itoa(m.publicReadWritePort))
		} else {
			// Use the read only port.
			hostAndPort = net.JoinHostPort(host, strconv.Itoa(m.publicReadOnlyPort))
			protocol = "http://"
		}
	}
	webServicesUrl := protocol + hostAndPort

	// Enable swagger UI and discovery API
	swaggerConfig := swagger.Config{
		WebServicesUrl:  webServicesUrl,
		WebServices:     m.handlerContainer.RegisteredWebServices(),
		ApiPath:         "/swaggerapi/",
		SwaggerPath:     "/swaggerui/",
		SwaggerFilePath: "/swagger-ui/",
	}
	swagger.RegisterSwaggerService(swaggerConfig, m.handlerContainer)
}

示例#7
文件: main.go 项目: evolsnow/robot

func main() {
	var configFile string
	var debug bool

	flag.StringVar(&configFile, "c", "config.json", "specify config file")
	flag.BoolVar(&debug, "d", false, "debug mode")
	flag.Parse()
	config, err := ParseConfig(configFile)
	if err != nil {
		log.Fatal("a vailid json config file must exist")
	}

	//connect to redis
	redisPort := strconv.Itoa(config.RedisPort)
	redisServer := net.JoinHostPort(config.RedisAddress, redisPort)
	if !conn.Ping(redisServer, config.RedisPassword) {
		log.Fatal("connect to redis server failed")
	}
	conn.Pool = conn.NewPool(redisServer, config.RedisPassword, config.RedisDB)

	//create robot and run
	robot := newRobot(config.RobotToken, config.RobotName, config.WebHookURL)
	robot.bot.Debug = debug
	go robot.run()

	//run server and web samaritan
	srvPort := strconv.Itoa(config.Port)
	http.HandleFunc("/ajax", ajax)
	http.HandleFunc("/websocket", socketHandler)
	http.HandleFunc("/groupTalk", groupTalk)
	log.Fatal(http.ListenAndServeTLS(net.JoinHostPort(config.Server, srvPort), config.Cert, config.CertKey, nil))

}

示例#8
文件: proxier_test.go 项目: asim/kubernetes

func TestUDPProxyUpdateDeleteUpdate(t *testing.T) {
	lb := NewLoadBalancerRR()
	lb.OnUpdate([]api.Endpoints{
		{
			JSONBase:  api.JSONBase{ID: "echo"},
			Endpoints: []string{net.JoinHostPort("127.0.0.1", udpServerPort)},
		},
	})

	p := NewProxier(lb, "127.0.0.1")

	proxyPort, err := p.addServiceOnUnusedPort("echo", "UDP", time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	conn, err := net.Dial("udp", net.JoinHostPort("127.0.0.1", proxyPort))
	if err != nil {
		t.Fatalf("error connecting to proxy: %v", err)
	}
	conn.Close()

	p.OnUpdate([]api.Service{})
	if err := waitForClosedPortUDP(p, proxyPort); err != nil {
		t.Fatalf(err.Error())
	}
	proxyPortNum, _ := strconv.Atoi(proxyPort)
	p.OnUpdate([]api.Service{
		{JSONBase: api.JSONBase{ID: "echo"}, Port: proxyPortNum, Protocol: "UDP"},
	})
	testEchoUDP(t, "127.0.0.1", proxyPort)
}

示例#9
文件: proxy.go 项目: z0rr0/121proxy

// New creates new proxy structure.
func New(filename string, debug bool) (*Proxy, error) {
	const ermsg string = "incorrect configuration parameter: %v"
	cfg, err := readConfig(filename)
	if err != nil {
		return nil, err
	}
	switch {
	case cfg.InPort == 0:
		err = fmt.Errorf(ermsg, "inport")
	case cfg.OutPort == 0:
		err = fmt.Errorf(ermsg, "outport")
	case len(cfg.OutHost) == 0:
		err = fmt.Errorf(ermsg, "outhost")
	case (cfg.Workers[0] == 0) || (cfg.Workers[1] == 0):
		fmt.Println("WARNING: workers is not configured, unlimited mode")
	}
	if err != nil {
		return nil, err
	}
	outAddr := make([]string, len(cfg.OutHost))
	for i, host := range cfg.OutHost {
		outAddr[i] = net.JoinHostPort(host, fmt.Sprint(cfg.OutPort))
	}
	p := &Proxy{
		cfg:      cfg,
		LogDebug: log.New(ioutil.Discard, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile),
		LogInfo:  log.New(os.Stderr, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile),
		inAddr:   net.JoinHostPort(cfg.InHost, fmt.Sprint(cfg.InPort)),
		outAddr:  outAddr,
	}
	if debug {
		p.LogDebug = log.New(os.Stdout, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile)
	}
	return p, nil
}

示例#10
文件: proxier_test.go 项目: asim/kubernetes

func TestUDPProxyStop(t *testing.T) {
	lb := NewLoadBalancerRR()
	lb.OnUpdate([]api.Endpoints{
		{
			JSONBase:  api.JSONBase{ID: "echo"},
			Endpoints: []string{net.JoinHostPort("127.0.0.1", udpServerPort)},
		},
	})

	p := NewProxier(lb, "127.0.0.1")

	proxyPort, err := p.addServiceOnUnusedPort("echo", "UDP", time.Second)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	conn, err := net.Dial("udp", net.JoinHostPort("127.0.0.1", proxyPort))
	if err != nil {
		t.Fatalf("error connecting to proxy: %v", err)
	}
	conn.Close()

	p.StopProxy("echo")
	// Wait for the port to really close.
	if err := waitForClosedPortUDP(p, proxyPort); err != nil {
		t.Fatalf(err.Error())
	}
}

示例#11
文件: proxier_test.go 项目: asim/kubernetes

func TestTCPProxyUpdateDelete(t *testing.T) {
	lb := NewLoadBalancerRR()
	lb.OnUpdate([]api.Endpoints{
		{
			JSONBase:  api.JSONBase{ID: "echo"},
			Endpoints: []string{net.JoinHostPort("127.0.0.1", tcpServerPort)},
		},
	})

	p := NewProxier(lb, "127.0.0.1")

	proxyPort, err := p.addServiceOnUnusedPort("echo", "TCP", 0)
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", proxyPort))
	if err != nil {
		t.Fatalf("error connecting to proxy: %v", err)
	}
	conn.Close()

	p.OnUpdate([]api.Service{})
	if err := waitForClosedPortTCP(p, proxyPort); err != nil {
		t.Fatalf(err.Error())
	}
}

示例#12
文件: networktest.go 项目: lightningnetwork/lnd

// newLightningNode creates a new test lightning node instance from the passed
// rpc config and slice of extra arguments.
func newLightningNode(rpcConfig *btcrpcclient.ConnConfig, lndArgs []string) (*lightningNode, error) {
	var err error

	cfg := &config{
		RPCHost: "127.0.0.1",
		RPCUser: rpcConfig.User,
		RPCPass: rpcConfig.Pass,
	}

	nodeNum := numActiveNodes
	cfg.DataDir, err = ioutil.TempDir("", "lndtest-data")
	if err != nil {
		return nil, err
	}
	cfg.LogDir, err = ioutil.TempDir("", "lndtest-log")
	if err != nil {
		return nil, err
	}

	cfg.PeerPort, cfg.RPCPort = generateListeningPorts()

	numActiveNodes++

	return &lightningNode{
		cfg:       cfg,
		p2pAddr:   net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.PeerPort)),
		rpcAddr:   net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.RPCPort)),
		rpcCert:   rpcConfig.Certificates,
		nodeId:    nodeNum,
		extraArgs: lndArgs,
	}, nil
}

示例#13
文件: ParseUnsolvedAddr.go 项目: keysonZZZ/kmg

func (uaddr UnsolvedAddr) String() string {
	if uaddr.Ip != nil {
		return net.JoinHostPort(uaddr.Ip.String(), strconv.Itoa(int(uaddr.Port)))
	} else {
		return net.JoinHostPort(uaddr.Domain, strconv.Itoa(int(uaddr.Port)))
	}
}

示例#14
文件: rpcserver.go 项目: kazcw/btcd

// newRPCServer returns a new instance of the rpcServer struct.
func newRPCServer(s *server) (*rpcServer, error) {
	rpc := rpcServer{
		server: s,
	}
	// Get values from config
	rpc.rpcport = cfg.RPCPort
	rpc.username = cfg.RPCUser
	rpc.password = cfg.RPCPass

	// IPv4 listener.
	var listeners []net.Listener
	listenAddr4 := net.JoinHostPort("127.0.0.1", rpc.rpcport)
	listener4, err := net.Listen("tcp4", listenAddr4)
	if err != nil {
		log.Errorf("[RPCS] Couldn't create listener: %v", err)
		return nil, err
	}
	listeners = append(listeners, listener4)

	// IPv6 listener.
	listenAddr6 := net.JoinHostPort("::1", rpc.rpcport)
	listener6, err := net.Listen("tcp6", listenAddr6)
	if err != nil {
		log.Errorf("[RPCS] Couldn't create listener: %v", err)
		return nil, err
	}
	listeners = append(listeners, listener6)

	rpc.listeners = listeners
	return &rpc, err
}

示例#15
文件: strategy.go 项目: robbfoster-taulia/kubernetes

// ResourceLocation returns an URL and transport which one can use to send traffic for the specified node.
func ResourceLocation(getter ResourceGetter, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper, ctx api.Context, id string) (*url.URL, http.RoundTripper, error) {
	schemeReq, name, portReq, valid := util.SplitSchemeNamePort(id)
	if !valid {
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid node request %q", id))
	}

	nodeObj, err := getter.Get(ctx, name)
	if err != nil {
		return nil, nil, err
	}
	node := nodeObj.(*api.Node)
	hostIP, err := nodeutil.GetNodeHostIP(node)
	if err != nil {
		return nil, nil, err
	}
	host := hostIP.String()

	if portReq == "" || strconv.Itoa(ports.KubeletPort) == portReq {
		// Ignore requested scheme, use scheme provided by GetConnectionInfo
		scheme, port, kubeletTransport, err := connection.GetConnectionInfo(host)
		if err != nil {
			return nil, nil, err
		}
		return &url.URL{
				Scheme: scheme,
				Host: net.JoinHostPort(
					host,
					strconv.FormatUint(uint64(port), 10),
				),
			},
			kubeletTransport,
			nil
	}
	return &url.URL{Scheme: schemeReq, Host: net.JoinHostPort(host, portReq)}, proxyTransport, nil
}

示例#16
文件: roundrobin.go 项目: driverpt/go-explorations

func (rrlb *RoundRobinLoadBalancer) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	_, endpoint, _ := rrlb.NextEndpoint()

	fmt.Println("Next Endpoint => " + net.JoinHostPort(endpoint.host.String(), endpoint.port))

	request.Header.Add("X-FORWARDED-FOR", request.RemoteAddr)
	request.Header.Add("Server", "Go Load Balancer")
	fmt.Println(request.Proto)
	client := &http.Client{}

	newRequest := new(http.Request)
	*newRequest = *request

	fmt.Println("Request URI => " + request.RequestURI)

	uri, _ := url.ParseRequestURI(request.RequestURI)

	if len(uri.Scheme) == 0 {
		uri.Scheme = "http"
	}

	newRequest.URL = uri

	newRequest.URL.Host = net.JoinHostPort(endpoint.host.String(), endpoint.port)
	newRequest.URL.User = request.URL.User

	newRequest.RequestURI = ""

	clientResponse, _ := client.Do(newRequest)

	clientResponse.Write(response)
}

示例#17
文件: goofclient.go 项目: GOOFS/go-goof-Talk

//CreateClientFromFlags function parses the command line arguments
func CreateClientFromFlags() (*ChatClient, error) {
	var c = &ChatClient{}
	var host string

	flag.StringVar(&c.Username, "user", "Goof", "Your username")
	flag.StringVar(&host, "host", "localhost", "The host you want to connect to")

	flag.Parse()
	if c.Username == "Goof" {
		fmt.Println("Enter your Goof ID: ")
		fmt.Scanln(&c.Username)
	}
	if !flag.Parsed() {
		return c, errors.New("Unable to create user from commandline flags. Please try again")
	}

	// Check for the structure of the flag to see if we can make any educated guesses for them
	if len(host) != 0 {

		if strings.HasPrefix(host, ":") { // Begins with a colon means :3410 (just port)
			c.Address = DefaultHost + host
		} else if strings.Contains(host, ":") { // Contains a colon means host:port
			c.Address = host
		} else { // Otherwise, it's just a host
			c.Address = net.JoinHostPort(host, strconv.Itoa(DefaultPort))
		}

	} else {
		c.Address = net.JoinHostPort(DefaultHost, strconv.Itoa(DefaultPort)) // Default to our default port and host
	}

	return c, nil
}

示例#18
文件: dns.go 项目: nightexcessive/ts3

// This looks up a TeamSpeak host, immitating the manner in which the TeamSpeak
// client looks it up. hostCombo should either be a host:port combination or a
// lone hostname. If a port is not specified, the default port of 9987 will be
// used.
func ResolveHost(hostCombo string) ([]string, error) {
	hostname, port, err := net.SplitHostPort(hostCombo)
	if addrErr, ok := err.(*net.AddrError); ok && addrErr.Err == "missing port in address" {
		hostname = hostCombo
		port = "9987"
	} else if err != nil {
		return nil, err
	}

	_, records, err := net.LookupSRV("ts3", "udp", hostname)
	if err != nil {
		return nil, err
	}

	if len(records) > 0 {
		hosts := make([]string, len(records))
		for i, record := range records {
			hosts[i] = net.JoinHostPort(record.Target, strconv.FormatInt(int64(record.Port), 10))
		}

		return hosts, nil
	}

	addrs, err := net.LookupIP(hostname)
	if err != nil {
		return nil, err
	}

	hosts := make([]string, len(addrs))
	for i, addr := range addrs {
		hosts[i] = net.JoinHostPort(addr.String(), port)
	}

	return hosts, nil
}

示例#19
文件: connections_tcp.go 项目: WeavingCode/syncthing

func makeTCPDialer(network string) DialerFactory {
	return func(uri *url.URL, tlsCfg *tls.Config) (*tls.Conn, error) {
		// Check that there is a port number in uri.Host, otherwise add one.
		host, port, err := net.SplitHostPort(uri.Host)
		if err != nil && strings.HasPrefix(err.Error(), "missing port") {
			// addr is on the form "1.2.3.4"
			uri.Host = net.JoinHostPort(uri.Host, "22000")
		} else if err == nil && port == "" {
			// addr is on the form "1.2.3.4:"
			uri.Host = net.JoinHostPort(host, "22000")
		}

		// Don't try to resolve the address before dialing. The dialer may be a
		// proxy, and we should let the proxy do the resolving in that case.
		conn, err := dialer.Dial(network, uri.Host)
		if err != nil {
			l.Debugln(err)
			return nil, err
		}

		tc := tls.Client(conn, tlsCfg)
		err = tc.Handshake()
		if err != nil {
			tc.Close()
			return nil, err
		}

		return tc, nil
	}
}

示例#20
文件: proxier_test.go 项目: htomika/kubernetes

func TestProxyStop(t *testing.T) {
	port, err := echoServer(t, "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}

	lb := NewLoadBalancerRR()
	lb.OnUpdate([]api.Endpoints{{JSONBase: api.JSONBase{ID: "echo"}, Endpoints: []string{net.JoinHostPort("127.0.0.1", port)}}})

	p := NewProxier(lb)

	proxyPort, err := p.addServiceOnUnusedPort("echo")
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", proxyPort))
	if err != nil {
		t.Fatalf("error connecting to proxy: %v", err)
	}
	conn.Close()

	p.StopProxy("echo")
	// Wait for the port to really close.
	time.Sleep(2 * time.Second)
	_, err = net.Dial("tcp", net.JoinHostPort("127.0.0.1", proxyPort))
	if err == nil {
		t.Fatalf("Unexpected non-error.")
	}
}

示例#21
文件: discovery.go 项目: Wind0r/prometheus

func (kd *Discovery) updateAPIServersTargetGroup() *config.TargetGroup {
	tg := &config.TargetGroup{
		Source: apiServersTargetGroupName,
		Labels: model.LabelSet{
			roleLabel: model.LabelValue("apiserver"),
		},
	}

	for _, apiServer := range kd.apiServers {
		apiServerAddress := apiServer.Host
		_, _, err := net.SplitHostPort(apiServerAddress)
		// If error then no port is specified - use default for scheme.
		if err != nil {
			switch apiServer.Scheme {
			case "http":
				apiServerAddress = net.JoinHostPort(apiServerAddress, "80")
			case "https":
				apiServerAddress = net.JoinHostPort(apiServerAddress, "443")
			}
		}

		t := model.LabelSet{
			model.AddressLabel: model.LabelValue(apiServerAddress),
			model.SchemeLabel:  model.LabelValue(apiServer.Scheme),
		}
		tg.Targets = append(tg.Targets, t)
	}

	return tg
}

示例#22
文件: client.go 项目: hakobe/paranoidhttp

func safeAddr(hostport string) (string, error) {
	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		return "", err
	}

	ip := net.ParseIP(host)
	if ip != nil {
		if ip.To4() != nil && isBadIPv4(ip) {
			return "", fmt.Errorf("bad ip is detected: %v", ip)
		}
		return net.JoinHostPort(ip.String(), port), nil
	}

	if isBadHost(host) {
		return "", fmt.Errorf("bad host is detected: %v", host)
	}

	ips, err := net.LookupIP(host) // TODO timeout
	if err != nil || len(ips) <= 0 {
		return "", err
	}
	for _, ip := range ips {
		if ip.To4() != nil && isBadIPv4(ip) {
			return "", fmt.Errorf("bad ip is detected: %v", ip)
		}
	}
	return net.JoinHostPort(ips[0].String(), port), nil
}

示例#23
文件: main.go 项目: yichengq/nameserver

func main() {
	configfn := "nameserver.conf"
	data, err := ioutil.ReadFile(configfn)
	if err != nil {
		log.Fatalf("server: cannot load configuration file[%s] (%v)", configfn, err)
	}

	var conf config.Server
	if _, err := toml.Decode(string(data), &conf); err != nil {
		log.Fatalf("server: configuration file[%s] is not valid (%v)", configfn, err)
	}
	server := NewServer()
	for i, v := range conf.Disks {
		log.Infof("Adding %v to disks", v)
		server.registeredDisks = append(server.registeredDisks, &conf.Disks[i])
	}
	log.Infof("server: starting server...")

	lis, err := net.Listen("tcp", net.JoinHostPort(conf.Bind, conf.Port))

	if err != nil {
		log.Fatalf("server: failed to listen: %v", err)
	}

	log.Infof("server: listening on %s", net.JoinHostPort(conf.Bind, conf.Port))

	s := grpc.NewServer()
	pb.RegisterNameServer(s, server)
	log.Infof("server: ready to serve clients")
	s.Serve(lis)
}

示例#24
文件: flags.go 项目: steelglove/cockroach

func init() {
	initFlags(context)

	cobra.OnInitialize(func() {
		if context.EphemeralSingleNode {
			context.Insecure = true
			if len(context.JoinUsing) != 0 {
				log.Errorf("--join cannot be specified when running a node in dev mode (--dev)")
				os.Exit(1)
			}
			fmt.Printf(`
****
**
** This node is being run in DEVELOPMENT mode.
**
** All data is ephemeral, and there is no security.
**
****

`)
		}
		context.Addr = net.JoinHostPort(connHost, connPort)
		context.PGAddr = net.JoinHostPort(connHost, connPGPort)
	})
}

示例#25
文件: transport.go 项目: fangdingjun/net

// authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
// and returns a host:port. The port 443 is added if needed.
func (t *Transport) authorityAddr(req *http.Request) (addr string) {
	//var err error

	h := req.URL.Host
	if h == "" {
		h = req.Host
	}

	/* no proxy */
	if t.Proxy == nil {
		if _, _, err := net.SplitHostPort(h); err != nil {
			return net.JoinHostPort(h, "443")
		}
		return h
	}

	/* get proxy */
	u, err := t.Proxy(req)
	if err != nil {
		if _, _, err := net.SplitHostPort(h); err != nil {
			return net.JoinHostPort(h, "443")
		}
		return h
	}

	if _, _, err := net.SplitHostPort(u.Host); err != nil {
		return net.JoinHostPort(u.Host, "443")
	}

	return u.Host
}

示例#26
文件: udp_pcp.go 项目: antongulenko/RTP

func (proxy *PcpProxy) StartProxyPair(val *pcp.StartProxyPair) (*pcp.StartProxyPairResponse, error) {
	target1 := net.JoinHostPort(val.ReceiverHost, strconv.Itoa(val.ReceiverPort1))
	target2 := net.JoinHostPort(val.ReceiverHost, strconv.Itoa(val.ReceiverPort2))
	udp1, udp2, err := NewUdpProxyPair(val.ProxyHost, target1, target2)
	if err != nil {
		return nil, err
	}

	port1, port2 := udp1.listenAddr.Port, udp2.listenAddr.Port
	port := port1
	if _, ok := proxy.sessions[port]; ok {
		// This should not happen due to the NewUdpProxyPair algorithm
		return nil, fmt.Errorf("Session already exists for one of the proxies on port %v or %v", port1, port2)
	}

	session := &udpSession{
		udp:   udp1,
		udp2:  udp2,
		port:  port,
		proxy: proxy,
	}
	proxy.sessions.StartSession(port, session)
	return &pcp.StartProxyPairResponse{
		ProxyHost:  val.ProxyHost,
		ProxyPort1: port1,
		ProxyPort2: port2,
	}, nil
}

示例#27
文件: api_test.go 项目: claudiu-coblis/juju

func mockedAPIState(flags mockedStateFlags) *mockAPIState {
	hasHostPort := flags&mockedHostPort == mockedHostPort
	hasEnvironTag := flags&mockedEnvironTag == mockedEnvironTag
	preferIPv6 := flags&mockedPreferIPv6 == mockedPreferIPv6
	addr := ""

	apiHostPorts := [][]network.HostPort{}
	if hasHostPort {
		var apiAddrs []network.Address
		ipv4Address := network.NewAddress("0.1.2.3")
		ipv6Address := network.NewAddress("2001:db8::1")
		if preferIPv6 {
			addr = net.JoinHostPort(ipv6Address.Value, "1234")
			apiAddrs = append(apiAddrs, ipv6Address, ipv4Address)
		} else {
			addr = net.JoinHostPort(ipv4Address.Value, "1234")
			apiAddrs = append(apiAddrs, ipv4Address, ipv6Address)
		}
		apiHostPorts = [][]network.HostPort{
			network.AddressesWithPort(apiAddrs, 1234),
		}
	}
	environTag := ""
	if hasEnvironTag {
		environTag = "environment-df136476-12e9-11e4-8a70-b2227cce2b54"
	}
	return &mockAPIState{
		apiHostPorts: apiHostPorts,
		environTag:   environTag,
		addr:         addr,
	}
}

示例#28
文件: store_test.go 项目: BobbWu/flynn

// NewStore returns a new instance of Store.
func NewStore() *Store {
	// Generate a temporary path.
	f, _ := ioutil.TempFile("", "discoverd-store-")
	f.Close()
	os.Remove(f.Name())

	// Initialize store.
	s := &Store{Store: server.NewStore(f.Name())}

	// Retrieve a random port.
	port := MustRandomPort()

	// Set default test settings.
	s.BindAddress = net.JoinHostPort("", port)
	s.Advertise, _ = net.ResolveTCPAddr("tcp", net.JoinHostPort("localhost", port))
	s.HeartbeatTimeout = 50 * time.Millisecond
	s.ElectionTimeout = 50 * time.Millisecond
	s.LeaderLeaseTimeout = 50 * time.Millisecond
	s.CommitTimeout = 5 * time.Millisecond
	s.EnableSingleNode = true

	// Turn off logs if verbose flag is not set.
	if !testing.Verbose() {
		s.LogOutput = ioutil.Discard
	}

	return s
}

示例#29
文件: agent.go 项目: imoapps/juju

// APIInfo is defined on Config interface.
func (c *configInternal) APIInfo() (*api.Info, bool) {
	if c.apiDetails == nil || c.apiDetails.addresses == nil {
		return nil, false
	}
	servingInfo, isStateServer := c.StateServingInfo()
	addrs := c.apiDetails.addresses
	if isStateServer {
		port := servingInfo.APIPort
		localAPIAddr := net.JoinHostPort("localhost", strconv.Itoa(port))
		if c.preferIPv6 {
			localAPIAddr = net.JoinHostPort("::1", strconv.Itoa(port))
		}
		addrInAddrs := false
		for _, addr := range addrs {
			if addr == localAPIAddr {
				addrInAddrs = true
				break
			}
		}
		if !addrInAddrs {
			addrs = append(addrs, localAPIAddr)
		}
	}
	return &api.Info{
		Addrs:      addrs,
		Password:   c.apiDetails.password,
		CACert:     c.caCert,
		Tag:        c.tag,
		Nonce:      c.nonce,
		EnvironTag: c.environment,
	}, true
}

示例#30
文件: rack.go 项目: tnextday/seaweedfs

func (r *Rack) GetOrCreateDataNode(ip string, port int, publicUrl string, maxVolumeCount int) *DataNode {
	if dn := r.FindDataNode(ip, port); dn != nil {
		dn.UpdateLastSeen()
		if dn.IsDead() {
			dn.SetDead(false)
			r.GetTopology().chanRecoveredDataNodes <- dn
			dn.UpAdjustMaxVolumeCountDelta(maxVolumeCount - dn.maxVolumeCount)
		}
		return dn
	}

	dn := NewDataNode(net.JoinHostPort(ip, strconv.Itoa(port)))
	dn.Ip = ip
	dn.Port = port
	if publicUrl == "" {
		publicUrl = net.JoinHostPort(ip, strconv.Itoa(port))
	} else if publicUrl[0] == ':' {
		publicUrl = net.JoinHostPort(ip, publicUrl[1:])
	}
	dn.PublicUrl = publicUrl
	dn.maxVolumeCount = maxVolumeCount
	dn.UpdateLastSeen()
	r.LinkChildNode(dn)
	return dn
}

展开阅读全文