當前位置: 首頁>>代碼示例>>Golang>>正文


Golang net.SplitHostPort函數代碼示例

本文整理匯總了Golang中net.SplitHostPort函數的典型用法代碼示例。如果您正苦於以下問題:Golang SplitHostPort函數的具體用法?Golang SplitHostPort怎麽用?Golang SplitHostPort使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了SplitHostPort函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: getPass

func getPass(r *http.Request) (user, pass string) {
	host, port, err := net.SplitHostPort(r.Host)
	if err != nil {
		host = r.Host
		if r.TLS != nil {
			port = "443"
		} else {
			port = "80"
		}
	}

	for _, h := range cfg.Host {
		host1, port1, _ := net.SplitHostPort(h.Host)
		if host1 == host && port == port1 {
			// host, port match
			return h.ProxyUser, h.ProxyPasswd
		} else if host1 == "" && port1 == port {
			// port match and host is wildcard
			return h.ProxyUser, h.ProxyPasswd
		} else if host1 == "0.0.0.0" && port == port1 {
			// port match and host is wildcard
			return h.ProxyUser, h.ProxyPasswd
		} else if host1 == "::" && port == port1 {
			// port match and host is wildcard
			return h.ProxyUser, h.ProxyPasswd
		}
	}
	return "", ""
}
開發者ID:fangdingjun,項目名稱:gpp,代碼行數:29,代碼來源:basic_auth.go

示例2: getARecords

func (s *Server) getARecords(q dns.Question) (records []dns.RR, err error) {
	var h string
	name := strings.TrimSuffix(q.Name, ".")

	// Leader should always be listed
	if name == "leader."+s.domain || name == "master."+s.domain || name == s.domain {
		h, _, err = net.SplitHostPort(s.Leader())

		if err != nil {
			return
		}

		records = append(records, &dns.A{Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 15}, A: net.ParseIP(h)})
	}

	if name == s.domain {
		for _, m := range s.Members() {
			h, _, err = net.SplitHostPort(m)

			if err != nil {
				return
			}

			records = append(records, &dns.A{Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 15}, A: net.ParseIP(h)})
		}
	}

	return
}
開發者ID:velebak,項目名稱:skydns,代碼行數:29,代碼來源:server.go

示例3: hostAddr

// hostAddr returns the host and port that remote nodes will use to reach this
// node.
func (s *Server) hostAddr() (string, string, error) {
	// Resolve host to address.
	_, port, err := net.SplitHostPort(s.BindAddress)
	if err != nil {
		return "", "", fmt.Errorf("split bind address: %s", err)
	}

	host := s.Hostname

	// See if we might have a port that will override the BindAddress port
	if host != "" && host[len(host)-1] >= '0' && host[len(host)-1] <= '9' && strings.Contains(host, ":") {
		hostArg, portArg, err := net.SplitHostPort(s.Hostname)
		if err != nil {
			return "", "", err
		}

		if hostArg != "" {
			host = hostArg
		}

		if portArg != "" {
			port = portArg
		}
	}
	return host, port, nil
}
開發者ID:Tony133,項目名稱:influxdb,代碼行數:28,代碼來源:server.go

示例4: authorityAddr

// 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
}
開發者ID:fangdingjun,項目名稱:net,代碼行數:33,代碼來源:transport.go

示例5: Validate

func (upstream *Upstream) Validate() (valid bool) {
	var host, port string
	host, port, err := net.SplitHostPort(upstream.Server)
	if err != nil {
		server := upstream.Server + ":25565"
		if host, port, err = net.SplitHostPort(server); err != nil {
			log.Error("Invalid upstream server: " + upstream.Server)
			return false
		}
		log.Infof("no port information found in %s, assume 25565", upstream.Server)
		upstream.Server = server
	}
	p, err := strconv.ParseUint(port, 10, 16)
	if err != nil {
		log.Errorf("Invalid port %s: %s", port, err.Error())
		return false
	}
	host = strings.ToLower(host)
	if !CheckHost(host) {
		log.Error("Invalid upstream host: " + host)
		return false
	}
	upstream.Server = net.JoinHostPort(host, fmt.Sprintf("%d", p))
	upstream.Pattern = strings.ToLower(upstream.Pattern)
	if !CheckPattern(upstream.Pattern) {
		log.Error("Invalid pattern: " + upstream.Pattern)
		return false
	}
	if upstream.ErrorMsg.Text == "" {
		log.Warnf("Empty error text for %s, use default string", upstream.Server)
		upstream.ErrorMsg.Text = "Connection failed to " + upstream.Server
	}
	upstream.ChatMsg = ToChatMsg(&upstream.ErrorMsg)
	return true
}
開發者ID:Elenw,項目名稱:MineGate-Go,代碼行數:35,代碼來源:upstream.go

示例6: validateReplication

func (wr *Wrangler) validateReplication(shardInfo *topo.ShardInfo, tabletMap map[topo.TabletAlias]*topo.TabletInfo, results chan<- vresult) {
	_, ok := tabletMap[shardInfo.MasterAlias]
	if !ok {
		results <- vresult{shardInfo.MasterAlias.String(), fmt.Errorf("master not in tablet map")}
		return
	}

	actionPath, err := wr.ai.GetSlaves(shardInfo.MasterAlias)
	if err != nil {
		results <- vresult{shardInfo.MasterAlias.String(), err}
		return
	}
	sa, err := wr.ai.WaitForCompletionReply(actionPath, wr.actionTimeout())
	if err != nil {
		results <- vresult{shardInfo.MasterAlias.String(), err}
		return
	}
	slaveAddrs := sa.(*tm.SlaveList).Addrs
	if len(slaveAddrs) == 0 {
		results <- vresult{shardInfo.MasterAlias.String(), fmt.Errorf("no slaves found")}
		return
	}

	// Some addresses don't resolve in all locations, just use IP address
	if err != nil {
		results <- vresult{shardInfo.MasterAlias.String(), fmt.Errorf("resolve slaves failed: %v", err)}
		return
	}

	tabletIpMap := make(map[string]*topo.Tablet)
	for _, tablet := range tabletMap {
		ipAddr, _, err := net.SplitHostPort(tablet.MysqlIpAddr)
		if err != nil {
			results <- vresult{tablet.Alias().String(), fmt.Errorf("bad mysql addr: %v %v", tablet.MysqlIpAddr, err)}
			continue
		}
		tabletIpMap[ipAddr] = tablet.Tablet
	}

	// See if every slave is in the replication graph.
	for _, slaveAddr := range slaveAddrs {
		if tabletIpMap[slaveAddr] == nil {
			results <- vresult{shardInfo.Keyspace() + "/" + shardInfo.ShardName(), fmt.Errorf("slave not in replication graph: %v (mysql instance without vttablet?)", slaveAddr)}
		}
	}

	// See if every entry in the replication graph is connected to the master.
	for _, tablet := range tabletMap {
		if !tablet.IsSlaveType() {
			continue
		}

		ipAddr, _, err := net.SplitHostPort(tablet.MysqlIpAddr)
		if err != nil {
			results <- vresult{tablet.Alias().String(), fmt.Errorf("bad mysql addr: %v", err)}
		} else if !strInList(slaveAddrs, ipAddr) {
			results <- vresult{tablet.Alias().String(), fmt.Errorf("slave not replicating: %v %q", ipAddr, slaveAddrs)}
		}
	}
}
開發者ID:ZhuoRoger,項目名稱:vitess,代碼行數:60,代碼來源:validator.go

示例7: resolveAddr

// Resolve an address string into a net.TCPAddr. We are a bit more strict than
// net.ResolveTCPAddr; we don't allow an empty host or port, and the host part
// must be a literal IP address.
func resolveAddr(addrStr string) (*net.TCPAddr, error) {
	ipStr, portStr, err := net.SplitHostPort(addrStr)
	if err != nil {
		// Before the fixing of bug #7011, tor doesn't put brackets around IPv6
		// addresses. Split after the last colon, assuming it is a port
		// separator, and try adding the brackets.
		parts := strings.Split(addrStr, ":")
		if len(parts) <= 2 {
			return nil, err
		}
		addrStr := "[" + strings.Join(parts[:len(parts)-1], ":") + "]:" + parts[len(parts)-1]
		ipStr, portStr, err = net.SplitHostPort(addrStr)
	}
	if err != nil {
		return nil, err
	}
	if ipStr == "" {
		return nil, net.InvalidAddrError(fmt.Sprintf("address string %q lacks a host part", addrStr))
	}
	if portStr == "" {
		return nil, net.InvalidAddrError(fmt.Sprintf("address string %q lacks a port part", addrStr))
	}
	ip := net.ParseIP(ipStr)
	if ip == nil {
		return nil, net.InvalidAddrError(fmt.Sprintf("not an IP string: %q", ipStr))
	}
	port, err := parsePort(portStr)
	if err != nil {
		return nil, err
	}
	return &net.TCPAddr{IP: ip, Port: port}, nil
}
開發者ID:OperatorFoundation,項目名稱:obfs4,代碼行數:35,代碼來源:transparent_udp.go

示例8: ConnectToPeer

func (s *Ethereum) ConnectToPeer(addr string) error {
	if s.peers.Len() < s.MaxPeers {
		var alreadyConnected bool

		eachPeer(s.peers, func(p *Peer, v *list.Element) {
			if p.conn == nil {
				return
			}
			phost, _, _ := net.SplitHostPort(p.conn.RemoteAddr().String())
			ahost, _, _ := net.SplitHostPort(addr)

			if phost == ahost {
				alreadyConnected = true
				return
			}
		})

		if alreadyConnected {
			return nil
		}

		peer := NewOutboundPeer(addr, s, s.serverCaps)

		s.peers.PushBack(peer)

		log.Printf("[SERV] Adding peer %d / %d\n", s.peers.Len(), s.MaxPeers)
	}

	return nil
}
開發者ID:GrimDerp,項目名稱:eth-go,代碼行數:30,代碼來源:ethereum.go

示例9: Know

func (lp *Peers) Know(peer, id string) bool {
	lp.Lock()
	defer lp.Unlock()

	for _, p := range lp.peerList {
		if p.id != id {
			continue
		}

		phost, _, err := net.SplitHostPort(p.address)
		if err != nil {
			return false
		}
		candidateHost, _, err := net.SplitHostPort(peer)
		if err != nil {
			return false
		}

		if phost == candidateHost {
			return true
		}
	}

	return false
}
開發者ID:rakoo,項目名稱:rakoshare,代碼行數:25,代碼來源:peers.go

示例10: filterAddr

func (s *store) filterAddr(addrs []string, filter string) ([]string, error) {
	host, port, err := net.SplitHostPort(filter)
	if err != nil {
		return nil, err
	}

	ip, err := net.ResolveIPAddr("ip", host)
	if err != nil {
		return nil, err
	}

	var joinPeers []string
	for _, addr := range addrs {
		joinHost, joinPort, err := net.SplitHostPort(addr)
		if err != nil {
			return nil, err
		}

		joinIp, err := net.ResolveIPAddr("ip", joinHost)
		if err != nil {
			return nil, err
		}

		// Don't allow joining ourselves
		if ip.String() == joinIp.String() && port == joinPort {
			continue
		}
		joinPeers = append(joinPeers, addr)
	}
	return joinPeers, nil
}
開發者ID:hawson,項目名稱:influxdb,代碼行數:31,代碼來源:store.go

示例11: SaveFeeds

// save a list of feeds to overwrite feeds.ini
func SaveFeeds(feeds []FeedConfig) (err error) {
	conf := configparser.NewConfiguration()
	for _, feed := range feeds {
		if len(feed.Name) == 0 {
			// don't do feed with no name
			continue
		}
		sect := conf.NewSection("feed-" + feed.Name)
		if len(feed.proxy_type) > 0 {
			sect.Add("proxy-type", feed.proxy_type)
		}
		phost, pport, _ := net.SplitHostPort(feed.proxy_addr)
		sect.Add("proxy-host", phost)
		sect.Add("proxy-port", pport)
		host, port, _ := net.SplitHostPort(feed.Addr)
		sect.Add("host", host)
		sect.Add("port", port)
		sync := "0"
		if feed.sync {
			sync = "1"
		}
		sect.Add("sync", sync)
		interval := feed.sync_interval / time.Second
		sect.Add("sync-interval", fmt.Sprintf("%d", int(interval)))
		sect.Add("username", feed.username)
		sect.Add("password", feed.passwd)
		sect = conf.NewSection(feed.Name)
		for k, v := range feed.policy.rules {
			sect.Add(k, v)
		}
	}
	return configparser.Save(conf, "feeds.ini")
}
開發者ID:ZiRo-,項目名稱:srndv2,代碼行數:34,代碼來源:config.go

示例12: Start

func (p *Peer) Start() {
	peerHost, peerPort, _ := net.SplitHostPort(p.conn.LocalAddr().String())
	servHost, servPort, _ := net.SplitHostPort(p.conn.RemoteAddr().String())

	if p.inbound {
		p.host, p.port = packAddr(peerHost, peerPort)
	} else {
		p.host, p.port = packAddr(servHost, servPort)
	}

	err := p.pushHandshake()
	if err != nil {
		peerlogger.Debugln("Peer can't send outbound version ack", err)

		p.Stop()

		return
	}

	go p.HandleOutbound()
	// Run the inbound handler in a new goroutine
	go p.HandleInbound()
	// Run the general update handler
	go p.update()

	// Wait a few seconds for startup and then ask for an initial ping
	time.Sleep(2 * time.Second)
	p.writeMessage(ethwire.NewMessage(ethwire.MsgPingTy, ""))
	p.pingStartTime = time.Now()

}
開發者ID:vmatekole,項目名稱:eth-go,代碼行數:31,代碼來源:peer.go

示例13: getUrl

// Creates the url based on the url configuration.
// Adds missing parts with defaults (scheme, host, port)
func getUrl(defaultScheme string, defaultPath string, rawUrl string) (string, error) {

	urlStruct, err := url.Parse(rawUrl)

	if err != nil {
		return "", err
	}

	host := ""
	port := ""

	// If url doesn't have a scheme, host is written into path. For example: 192.168.3.7
	if urlStruct.Host == "" {
		urlStruct.Host = urlStruct.Path
		urlStruct.Path = ""
	}

	// Checks if split host works
	_, _, err = net.SplitHostPort(urlStruct.Host)

	// Only does split host if no errors
	if err == nil {
		host, port, err = net.SplitHostPort(urlStruct.Host)
		if err != nil {
			return "", err
		}
	} else {
		host = urlStruct.Host
	}

	// Assign default host if not set
	if host == "" {
		host = "localhost"
	}

	// Assign default port if not set
	if port == "" {
		port = "9200"
	}

	// Assign default scheme if not set
	if urlStruct.Scheme == "" {
		urlStruct.Scheme = defaultScheme
	}

	// Assign default path if not set
	if urlStruct.Path == "" {
		urlStruct.Path = defaultPath
	}

	// Check if ipv6
	if strings.Count(host, ":") > 1 && strings.Count(host, "]") == 0 {
		host = "[" + host + "]"
	}

	urlStruct.Host = host + ":" + port

	return urlStruct.String(), nil

}
開發者ID:monicasarbu,項目名稱:topbeat,代碼行數:62,代碼來源:output.go

示例14: TestResolveRecoverAddr

func (s *PeerSuite) TestResolveRecoverAddr(c *gc.C) {
	for _, testHostPort := range []string{"147.26.10.11:11370", "[fe80::d0dd:7dff:fefc:a828]:11370"} {
		reconAddr, err := net.ResolveTCPAddr("tcp", testHostPort)
		c.Assert(err, gc.IsNil)

		testHost, _, err := net.SplitHostPort(testHostPort)
		c.Assert(err, gc.IsNil)

		c.Assert(reconAddr.Port, gc.Equals, 11370)
		r := &Recover{
			RemoteAddr: reconAddr,
			RemoteConfig: &Config{
				HTTPPort: 8080,
			},
		}

		hkpHostPort, err := r.HkpAddr()
		c.Assert(err, gc.IsNil)

		hkpAddr, err := net.ResolveTCPAddr("tcp", hkpHostPort)
		c.Assert(err, gc.IsNil)

		hkpHost, _, err := net.SplitHostPort(hkpHostPort)
		c.Assert(err, gc.IsNil)

		c.Assert(hkpAddr.Port, gc.Equals, 8080)
		c.Assert(reconAddr.IP, gc.DeepEquals, hkpAddr.IP)
		c.Assert(testHost, gc.Equals, hkpHost)
	}
}
開發者ID:cmars,項目名稱:conflux,代碼行數:30,代碼來源:peer_test.go

示例15: Start

func (p *Peer) Start() {
	peerHost, peerPort, _ := net.SplitHostPort(p.conn.LocalAddr().String())
	servHost, servPort, _ := net.SplitHostPort(p.conn.RemoteAddr().String())

	if p.inbound {
		p.host, p.port = packAddr(peerHost, peerPort)
	} else {
		p.host, p.port = packAddr(servHost, servPort)
	}

	err := p.pushHandshake()
	if err != nil {
		ethutil.Config.Log.Debugln("Peer can't send outbound version ack", err)

		p.Stop()

		return
	}

	// Run the outbound handler in a new goroutine
	go p.HandleOutbound()
	// Run the inbound handler in a new goroutine
	go p.HandleInbound()

}
開發者ID:GrimDerp,項目名稱:eth-go,代碼行數:25,代碼來源:peer.go


注:本文中的net.SplitHostPort函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。