我正在用Golang编写我的第一个程序,或者更确切地说是修改一个模板,如果你愿意的话。希望解析yaml文件中的值。
apiVersion: "backend.example.com/v1alpha1"
kind: "Example"
metadata:
name: "solar-demo"
spec:
size: 2
group: backend.example.com
names:
kind: Example
listKind: ExampleList
plural: solar-demos
singular: solar-demo
scope: Namespaced
version: v1alpha1
pods:
- name: api
image: "shmukler/docker_solar-api"
port: 3000
command: '{"npm", "run", "start-api"}'
- name: service
image: "shmukler/docker_solar-svc"
port: 3001
command: '{"npm", "run", "start-solar-svc"}'
要解析出变量,我需要:
type Example struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
Spec ExampleSpec `json:"spec"`
Status ExampleStatus `json:"status,omitempty"`
}
type ExampleSpec struct {
Size int32 `json:"size"`
// Pods []ExamplePod `json:"pods"`
}
type ExampleStatus struct {
Nodes []string `json:"nodes"`
}
type ExamplePod struct {
Name []string `json:"name"`
Image []string `json:"image"`
Port int32 `json:"port"`
Command []string `json:"command"`
}
如果我注释掉Pods []ExamplePod
行,代码可以工作,尽管不解析Pods数组。如果我把它放在里面,当我传递yaml
文档- Observed a panic: &errors.errorString{s:"failed to decode json data with gvk...
时,就会出现错误。
我想将pods
加入到ExamplePod
类型的结构数组中。
今天是我学习围棋语言的第一天。抱歉问了个愚蠢的问题。我的yaml,JSON
表示中的相关片段。
spec":{
"group":"backend.example.com",
"names":{
"kind”:”Example”,
"listKind”:”ExampleList",
"plural":"solar-demos",
"singular":"solar-demo"
},
"pods":[
{
"command":"{\"npm\", \"run\", \"start-api\"}",
"image":"shmukler/docker_solar-api",
"name":"api",
"port":3000
},
{
"command":"{\"npm\", \"run\", \"start-solar-svc\"}",
"image":"shmukler/docker_solar-svc",
"name":"service",
"port":3001
}
],
"scope":"Namespaced",
"size":2,
"version":"v1alpha1"
}
我可以很好地得到example.Spec.Size
。我缺少的是pods
数组。
发布于 2018-07-12 09:26:25
使用这两个提供的答案的建议将YAML更改为:
containers:
- name: api
image: "shmukler/docker_solar-api"
port: 3000
command: ["npm", "run", "start-api"]
- name: service
image: "shmukler/docker_solar-svc"
port: 3001
command: ["npm", "run", "start-solar-svc"]
然后,更新定义,以便:
type Spec struct {
Size int32 `json:"size"`
Containers []Container `json:"containers"`
}
type Status struct {
Nodes []string `json:"nodes"`
}
type Container struct {
Name string `json:"name"`
Image string `json:"image"`
Port int32 `json:"port"`
Command []string `json:"command"`
}
终于成功了。
谢谢您的回答,帮助我理解了Golang类型定义是如何工作的。
发布于 2018-07-10 21:47:58
JSON无效。将”
替换为"
,并添加周围的{}
。
将ExamplePod字段的类型更改为字符串:
type ExamplePod struct {
Name string `json:"name"`
Image string `json:"image"`
Port int32 `json:"port"`
Command string `json:"command"`
}
https://stackoverflow.com/questions/51273806
复制相似问题