Skip to content

Commit 32734c3

Browse files
committed
chore: add crd client-go example
1 parent f2f5e63 commit 32734c3

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

.todo.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727

2828
[?] https://github.com/samber/lo
2929
[?] loki: https://github.com/piupuer/gin-web
30-
[?] 使用 clientBuilder,参考clusternet-agent源码
3130
[?] 使用 gin + mysql 实现类似kube-apiserver
3231
[?] loft 调研
3332
[?] onex-apiserver 后端对接 ES
@@ -131,3 +130,4 @@
131130
[] 缓存服务添加
132131
[] 项目文档补全
133132
[] 课程目录补全(精细版)
133+
[] 使用 clientBuilder,参考clusternet-agent源码

examples/client-go/crd/main.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
8+
"k8s.io/apimachinery/pkg/api/errors"
9+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
10+
"k8s.io/apimachinery/pkg/runtime/schema"
11+
"k8s.io/client-go/dynamic"
12+
"k8s.io/client-go/tools/clientcmd"
13+
)
14+
15+
func main() {
16+
configLoader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
17+
clientcmd.NewDefaultClientConfigLoadingRules(),
18+
&clientcmd.ConfigOverrides{},
19+
)
20+
21+
namespace, _, err := configLoader.Namespace()
22+
if err != nil {
23+
panic(err)
24+
}
25+
26+
cfg, err := configLoader.ClientConfig()
27+
if err != nil {
28+
panic(err)
29+
}
30+
31+
dc, err := dynamic.NewForConfig(cfg)
32+
if err != nil {
33+
panic(err)
34+
}
35+
36+
// identify out custom resource
37+
gvr := schema.GroupVersionResource{
38+
Group: "webapp.my.domain",
39+
Version: "v1",
40+
Resource: "guestbooks",
41+
}
42+
// retrieve the resource of kind Pizza named 'margherita'
43+
res, err := dc.Resource(gvr).
44+
Namespace(namespace).
45+
Get(context.TODO(), "guestbook-sample", metav1.GetOptions{})
46+
if err != nil {
47+
if errors.IsNotFound(err) {
48+
return
49+
}
50+
panic(err)
51+
}
52+
data, _ := json.Marshal(res)
53+
fmt.Println(string(data))
54+
55+
// grab the status if exists
56+
status, ok := res.Object["status"]
57+
if !ok {
58+
// otherwise create it
59+
status = make(map[string]interface{})
60+
}
61+
62+
// change the 'margherita' price
63+
status.(map[string]interface{})["cost"] = 6.50
64+
res.Object["status"] = status
65+
66+
// update the 'margherita' custom resource with the new price
67+
_, err = dc.Resource(gvr).Namespace(namespace).Update(context.TODO(), res, metav1.UpdateOptions{})
68+
if err != nil {
69+
panic(err)
70+
}
71+
}

0 commit comments

Comments
 (0)