...

Source file src/go.mongodb.org/mongo-driver/mongo/address/addr.go

Documentation: go.mongodb.org/mongo-driver/mongo/address

     1  // Copyright (C) MongoDB, Inc. 2017-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  // Package address provides structured representations of network addresses.
     8  package address // import "go.mongodb.org/mongo-driver/mongo/address"
     9  
    10  import (
    11  	"net"
    12  	"strings"
    13  )
    14  
    15  const defaultPort = "27017"
    16  
    17  // Address is a network address. It can either be an IP address or a DNS name.
    18  type Address string
    19  
    20  // Network is the network protocol for this address. In most cases this will be
    21  // "tcp" or "unix".
    22  func (a Address) Network() string {
    23  	if strings.HasSuffix(string(a), "sock") {
    24  		return "unix"
    25  	}
    26  	return "tcp"
    27  }
    28  
    29  // String is the canonical version of this address, e.g. localhost:27017,
    30  // 1.2.3.4:27017, example.com:27017.
    31  func (a Address) String() string {
    32  	// TODO: unicode case folding?
    33  	s := strings.ToLower(string(a))
    34  	if len(s) == 0 {
    35  		return ""
    36  	}
    37  	if a.Network() != "unix" {
    38  		_, _, err := net.SplitHostPort(s)
    39  		if err != nil && strings.Contains(err.Error(), "missing port in address") {
    40  			s += ":" + defaultPort
    41  		}
    42  	}
    43  
    44  	return s
    45  }
    46  
    47  // Canonicalize creates a canonicalized address.
    48  func (a Address) Canonicalize() Address {
    49  	return Address(a.String())
    50  }
    51  

View as plain text