/
provider.go
83 lines (73 loc) · 2.06 KB
/
provider.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
// Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package discover
import (
"fmt"
"net/url"
"github.com/erda-project/erda-infra/base/servicehub"
"github.com/erda-project/erda/pkg/discover"
servicediscover "github.com/erda-project/erda/providers/service-discover"
)
type config struct {
URLs map[string][]string `file:"urls"`
}
// +provider
type provider struct {
Cfg *config
urls map[string][]*url.URL
}
func (p *provider) Init(ctx servicehub.Context) (err error) {
p.urls = make(map[string][]*url.URL)
for service, urls := range p.Cfg.URLs {
for _, item := range urls {
u, err := url.Parse(item)
if err != nil {
return err
}
p.urls[service] = append(p.urls[service], u)
}
}
return nil
}
var _ servicediscover.Interface = (*provider)(nil)
func (p *provider) Endpoint(scheme, service string) (string, error) {
for _, u := range p.urls[service] {
if u.Scheme == scheme {
return u.Host, nil
}
}
return discover.GetEndpoint(service)
}
func (p *provider) ServiceURL(scheme, service string) (string, error) {
for _, u := range p.urls[service] {
if u.Scheme == scheme {
return u.String(), nil
}
}
addr, err := discover.GetEndpoint(service)
if err != nil {
return "", err
}
return fmt.Sprintf("%s://%s", scheme, addr), nil
}
func init() {
servicehub.Register("erda-discover", &servicehub.Spec{
Services: []string{"discover"},
Description: "discover all services",
ConfigFunc: func() interface{} { return &config{} },
Creator: func() servicehub.Provider {
return &provider{}
},
})
}