|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/fystack/mpcium/pkg/constant" |
| 8 | + "github.com/fystack/mpcium/pkg/logger" |
| 9 | + "github.com/hashicorp/consul/api" |
| 10 | + "github.com/spf13/viper" |
| 11 | +) |
| 12 | + |
| 13 | +func GetConsulClient(environment string) *api.Client { |
| 14 | + config := api.DefaultConfig() |
| 15 | + if environment == constant.EnvProduction { |
| 16 | + config.Token = viper.GetString("consul.token") |
| 17 | + username := viper.GetString("consul.username") |
| 18 | + password := viper.GetString("consul.password") |
| 19 | + if username != "" || password != "" { |
| 20 | + config.HttpAuth = &api.HttpBasicAuth{ |
| 21 | + Username: username, |
| 22 | + Password: password, |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + config.Address = viper.GetString("consul.address") |
| 28 | + config.WaitTime = 10 * time.Second |
| 29 | + // Ping the Consul server to verify connectivity |
| 30 | + |
| 31 | + client, err := api.NewClient(config) |
| 32 | + if err != nil { |
| 33 | + logger.Fatal("Failed to create consul client", err) |
| 34 | + } |
| 35 | + |
| 36 | + _, err = client.Status().Leader() |
| 37 | + if err != nil { |
| 38 | + logger.Fatal("failed to connect to Consul", err) |
| 39 | + } |
| 40 | + |
| 41 | + return client |
| 42 | +} |
| 43 | + |
| 44 | +func main() { |
| 45 | + fmt.Println("Debug consul script") |
| 46 | + config := api.DefaultConfig() |
| 47 | + config.Address = "http://localhost:8500" |
| 48 | + config.Token = "" |
| 49 | + config.WaitTime = 10 * time.Second |
| 50 | + // Ping the Consul server to verify connectivity |
| 51 | + |
| 52 | + client, err := api.NewClient(config) |
| 53 | + if err != nil { |
| 54 | + logger.Fatal("Failed to create consul client", err) |
| 55 | + } |
| 56 | + |
| 57 | + _, err = client.Status().Leader() |
| 58 | + if err != nil { |
| 59 | + logger.Fatal("failed to connect to Consul", err) |
| 60 | + } |
| 61 | + |
| 62 | + kv := client.KV() |
| 63 | + pairs, _, err := kv.List("mpc_peers/", nil) |
| 64 | + if err != nil { |
| 65 | + logger.Fatal("Error loading keys", err) |
| 66 | + } |
| 67 | + |
| 68 | + for _, pair := range pairs { |
| 69 | + fmt.Printf("Key: %s, Value: %s\n", pair.Key, string(pair.Value)) |
| 70 | + } |
| 71 | +} |
0 commit comments