gsvc_endpoint.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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/gogf/gf.
  6. // Package gsvc provides service registry and discovery definition.
  7. package gsvc
  8. import (
  9. "fmt"
  10. "github.com/gogf/gf/v2/errors/gcode"
  11. "github.com/gogf/gf/v2/errors/gerror"
  12. "github.com/gogf/gf/v2/text/gstr"
  13. "github.com/gogf/gf/v2/util/gconv"
  14. )
  15. // LocalEndpoint implements interface Endpoint.
  16. type LocalEndpoint struct {
  17. host string // host can be either IPv4 or IPv6 address.
  18. port int // port is port as commonly known.
  19. }
  20. // NewEndpoint creates and returns an Endpoint from address string of pattern "host:port",
  21. // eg: "192.168.1.100:80".
  22. func NewEndpoint(address string) Endpoint {
  23. array := gstr.SplitAndTrim(address, endpointHostPortDelimiter)
  24. if len(array) != 2 {
  25. panic(gerror.NewCodef(
  26. gcode.CodeInvalidParameter,
  27. `invalid address "%s" for creating endpoint, endpoint address is like "ip:port"`,
  28. address,
  29. ))
  30. }
  31. return &LocalEndpoint{
  32. host: array[0],
  33. port: gconv.Int(array[1]),
  34. }
  35. }
  36. // Host returns the IPv4/IPv6 address of a service.
  37. func (e *LocalEndpoint) Host() string {
  38. return e.host
  39. }
  40. // Port returns the port of a service.
  41. func (e *LocalEndpoint) Port() int {
  42. return e.port
  43. }
  44. // String formats and returns the Endpoint as a string, like: 192.168.1.100:80.
  45. func (e *LocalEndpoint) String() string {
  46. return fmt.Sprintf(`%s:%d`, e.host, e.port)
  47. }