endpoint.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2022 The OpenZipkin Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package zipkin
  15. import (
  16. "fmt"
  17. "net"
  18. "strconv"
  19. "strings"
  20. "github.com/openzipkin/zipkin-go/model"
  21. )
  22. // NewEndpoint creates a new endpoint given the provided serviceName and
  23. // hostPort.
  24. func NewEndpoint(serviceName string, hostPort string) (*model.Endpoint, error) {
  25. e := &model.Endpoint{
  26. ServiceName: serviceName,
  27. }
  28. if hostPort == "" || hostPort == ":0" {
  29. if serviceName == "" {
  30. // if all properties are empty we should not have an Endpoint object.
  31. return nil, nil
  32. }
  33. return e, nil
  34. }
  35. if strings.IndexByte(hostPort, ':') < 0 {
  36. hostPort += ":0"
  37. }
  38. host, port, err := net.SplitHostPort(hostPort)
  39. if err != nil {
  40. return nil, err
  41. }
  42. p, err := strconv.ParseUint(port, 10, 16)
  43. if err != nil {
  44. return nil, err
  45. }
  46. e.Port = uint16(p)
  47. addrs, err := net.LookupIP(host)
  48. if err != nil {
  49. return nil, fmt.Errorf("host lookup failure: %w", err)
  50. }
  51. for i := range addrs {
  52. addr := addrs[i].To4()
  53. if addr == nil {
  54. // IPv6 - 16 bytes
  55. if e.IPv6 == nil {
  56. e.IPv6 = addrs[i].To16()
  57. }
  58. } else {
  59. // IPv4 - 4 bytes
  60. if e.IPv4 == nil {
  61. e.IPv4 = addr
  62. }
  63. }
  64. if e.IPv4 != nil && e.IPv6 != nil {
  65. // Both IPv4 & IPv6 have been set, done...
  66. break
  67. }
  68. }
  69. return e, nil
  70. }