github.com/wangyougui/gf/v2@v2.6.5/net/gsvc/gsvc_endpoint.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  // Package gsvc provides service registry and discovery definition.
     8  package gsvc
     9  
    10  import (
    11  	"fmt"
    12  
    13  	"github.com/wangyougui/gf/v2/errors/gcode"
    14  	"github.com/wangyougui/gf/v2/errors/gerror"
    15  	"github.com/wangyougui/gf/v2/text/gstr"
    16  	"github.com/wangyougui/gf/v2/util/gconv"
    17  )
    18  
    19  // LocalEndpoint implements interface Endpoint.
    20  type LocalEndpoint struct {
    21  	host string // host can be either IPv4 or IPv6 address.
    22  	port int    // port is port as commonly known.
    23  }
    24  
    25  // NewEndpoint creates and returns an Endpoint from address string of pattern "host:port",
    26  // eg: "192.168.1.100:80".
    27  func NewEndpoint(address string) Endpoint {
    28  	array := gstr.SplitAndTrim(address, EndpointHostPortDelimiter)
    29  	if len(array) != 2 {
    30  		panic(gerror.NewCodef(
    31  			gcode.CodeInvalidParameter,
    32  			`invalid address "%s" for creating endpoint, endpoint address is like "ip:port"`,
    33  			address,
    34  		))
    35  	}
    36  	return &LocalEndpoint{
    37  		host: array[0],
    38  		port: gconv.Int(array[1]),
    39  	}
    40  }
    41  
    42  // Host returns the IPv4/IPv6 address of a service.
    43  func (e *LocalEndpoint) Host() string {
    44  	return e.host
    45  }
    46  
    47  // Port returns the port of a service.
    48  func (e *LocalEndpoint) Port() int {
    49  	return e.port
    50  }
    51  
    52  // String formats and returns the Endpoint as a string, like: 192.168.1.100:80.
    53  func (e *LocalEndpoint) String() string {
    54  	return fmt.Sprintf(`%s:%d`, e.host, e.port)
    55  }