Envoy 配置导出 YAML 文件

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
package main

import (
"bytes"
"encoding/json"
"os"
"testing"

"gopkg.in/yaml.v3"

"google.golang.org/protobuf/encoding/protojson"

bootstrap "github.com/envoyproxy/go-control-plane/envoy/config/bootstrap/v3"
cluster "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
core "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
)

func TestGenBootstrapYAML(t *testing.T) {
cfg, err := initConfig("config.yaml")
if err != nil {
t.Fatal(err)
}

b := &bootstrap.Bootstrap{
Admin: &bootstrap.Admin{
AccessLog: nil,
Address: &core.Address{
Address: &core.Address_SocketAddress{
SocketAddress: &core.SocketAddress{
Address: "0.0.0.0",
PortSpecifier: &core.SocketAddress_PortValue{
PortValue: 9901,
},
},
},
},
},
StaticResources: &bootstrap.Bootstrap_StaticResources{
Listeners: make([]*listener.Listener, 2),
Clusters: make([]*cluster.Cluster, len(cfg.Clusters)),
},
}

virtualHosts := genVirtualHosts(cfg)

b.StaticResources.Listeners[0] = makeListener(ListenerHTTPPort, false, virtualHosts)
b.StaticResources.Listeners[1] = makeListener(ListenerHTTPSPort, true, virtualHosts)

for i := 0; i < len(cfg.Clusters); i++ {
b.StaticResources.Clusters[i] = makeCluster(cfg.Clusters[i])
}

mo := protojson.MarshalOptions{UseProtoNames: true}

bs, err := mo.Marshal(b)
if err != nil {
t.Fatal(err)
}

var v any

err = json.Unmarshal(bs, &v)
if err != nil {
t.Fatal(err)
}

bb := &bytes.Buffer{}
ye := yaml.NewEncoder(bb)
ye.SetIndent(2)
defer func() { _ = ye.Close() }()

err = ye.Encode(v)
if err != nil {
t.Fatal(err)
}

err = os.WriteFile("envoy-bootstrap.yaml", bb.Bytes(), 0644)
if err != nil {
t.Fatal(err)
}
}