This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshalling.go
112 lines (90 loc) · 2.38 KB
/
marshalling.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package eureka
import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/hudl/fargo"
"github.com/micro/go-micro/registry"
)
func appToService(app *fargo.Application) []*registry.Service {
serviceMap := make(map[string]*registry.Service)
for _, instance := range app.Instances {
id := instance.Id()
addr := instance.IPAddr
port := instance.Port
var version string
var metadata map[string]string
var endpoints []*registry.Endpoint
// get version
k, err := instance.Metadata.GetString("version")
if err != nil {
continue
}
k, err = instance.Metadata.GetString("endpoints")
if err == nil {
json.Unmarshal([]byte(k), &endpoints)
}
k, err = instance.Metadata.GetString("metadata")
if err == nil {
json.Unmarshal([]byte(k), &metadata)
}
// get existing service
service, ok := serviceMap[version]
if !ok {
// create new if doesn't exist
service = ®istry.Service{
Name: strings.ToLower(app.Name),
Version: version,
Endpoints: endpoints,
}
}
// append node
service.Nodes = append(service.Nodes, ®istry.Node{
Id: id,
Address: addr,
Port: port,
Metadata: metadata,
})
// save
serviceMap[version] = service
}
var services []*registry.Service
for _, service := range serviceMap {
services = append(services, service)
}
return services
}
// only parses first node
func serviceToInstance(service *registry.Service) (*fargo.Instance, error) {
if len(service.Nodes) == 0 {
return nil, errors.New("Require nodes")
}
node := service.Nodes[0]
instance := &fargo.Instance{
App: service.Name,
HostName: node.Address,
IPAddr: node.Address,
VipAddress: node.Address,
SecureVipAddress: node.Address,
Port: node.Port,
Status: fargo.UP,
UniqueID: func(i fargo.Instance) string {
return fmt.Sprintf("%s:%s", node.Address, node.Id)
},
DataCenterInfo: fargo.DataCenterInfo{Name: fargo.MyOwn},
}
// set version
instance.SetMetadataString("version", service.Version)
// set instance ID
instance.SetMetadataString("instanceId", node.Id)
// set endpoints
if b, err := json.Marshal(service.Endpoints); err == nil {
instance.SetMetadataString("endpoints", string(b))
}
// set metadata
if b, err := json.Marshal(node.Metadata); err == nil {
instance.SetMetadataString("metadata", string(b))
}
return instance, nil
}