有没有大佬帮忙看看这个异常是怎么回事?

2022-05-30 14:54:19 +08:00
 wzcloud

在看 kubernetes 的 operator 开发教程,尝试着跑了下教程里面的代码,但是报错了(教程视频里面是正常运行的):

package main

import (
	"context"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	//config
	config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeDir)
	config.GroupVersion = new(schema.GroupVersion)
	config.GroupVersion.Group = ""
	config.GroupVersion.Version = "v1"
	config.NegotiatedSerializer = scheme.Codecs
	config.APIPath = "/api"
	if err != nil {
		panic(err)
	}

	//client
	restClient, err := rest.RESTClientFor(config)
	if err != nil {
		panic(err)
	}

	//get data
	pod := v1.Pod{}
	err = restClient.Get().Namespace("default").Resource("pods").Name("test").Do(context.TODO()).Into(&pod)
	if err != nil {
		println(err)
	} else {
		println(pod.Name)
	}
}

运行报错信息如下: panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x102e432b8]

goroutine 1 [running]: main.main() /Users/xxx/main.go:15 +0x58

进程 已完成,退出代码为 2

补充说明:

关于第十五行的结构体定义如下:

type ContentConfig struct {
	
	AcceptContentTypes string
	
	ContentType string
	
	GroupVersion *schema.GroupVersion
	
	NegotiatedSerializer runtime.NegotiatedSerializer
}

我自己的本地运行环境是 MacOS12+GO1.18.2 。

尝试把第十五行改成config.GroupVersion = &v1.SchemeGroupVersion也不行,一样的报错信息。。。

1314 次点击
所在节点    Go 编程语言
3 条回复
colatin
2022-05-30 14:59:33 +08:00
显然 clientcmd.BuildConfigFromFlags 出错了,把 err 打出来
wzcloud
2022-05-30 15:01:37 +08:00
@colatin 嗯。。刚刚看了下,把赋值语句放到 if err 前面去了。。
muchengxue
2022-05-30 15:15:11 +08:00
报错信息提示的很明确,访问了不存在的内存地址或者空指针,看不出来的话,建议用 ide 的 debug 一行一行的看。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/856219

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX