import "encoding/json"
Si vous spécifiez un tableau comme argument du package json, il sera converti.
data, _ := json.Marshal(m)
package main
import (
"context"
"encoding/json"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"log"
"os"
"path/filepath"
)
func main() {
//Spécifiez le chemin du fichier de Kubeconfig
kubeconfig := filepath.Join(os.Getenv("HOME"), ".kube", "config")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatal(err)
}
//Charger Kubeconfig
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
//Appeler la liste des pods
namespace := "default"
pods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})
if err != nil {
log.Fatalln("failed to get pods:", err)
}
m := map[string]string{}
// print pods
// pods.Items: []v1.Pod
for _, pod := range pods.Items {
m[pod.Name] = string(pod.Status.Phase)
}
data, _ := json.Marshal(m)
fmt.Printf(string(data))
}
Résultat d'exécution
{
"external-dns-547f4784f7-852zf": "Running",
"nginx-deployment-574b87c764-8vwdz": "Running",
"nginx-deployment-574b87c764-dnr6m": "Running",
"v01-app-54fc4b5d44-k5zfp": "Running",
"v01-db-5b756dc6b-57grv": "Running"
}
Le maréchal est-il un maréchal? veux dire? Barbe Noire?
marshal --Utilisé lors de la conversion de struct en json
unmarshal
Recommended Posts