CentOS 安装 Go环境并配置goproxy
wget https://dl.google.com/go/go1.14.4.linux-amd64.tar.gz
tar -xzvf go1.14.4.linux-amd64.tar.gz -C /usr/local/
mkdir -p /home/gopath
cat >> /etc/profile <<EOF
export GOROOT=/usr/local/go
export GOPATH=/home/gopath
export PATH=\$PATH:\$GOPATH/bin
EOF
source /etc/profile
go version
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
在工程中新建一个名为go.mod
的文件,在其中加入module
和require
两个内容,如图所示:
module go2go 1.15require k8s.io/client-go kubernetes-1.15.0
然后新建你的main.go
文件,就可以在程序中调用clien-go
工具包了。在第一次运行程序后,client-go
工具包的相关组件就会被自动拽取到本地环境中。只是此后所有需要用到client-go
的程序中都须加入go.mod
文件。
5. 在k8s集群外读取pod资源示例
package mainimport ("flag""fmt""os""path/filepath""time""k8s.io/apimachinery/pkg/api/errors"metav1 "k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/client-go/kubernetes""k8s.io/client-go/tools/clientcmd"
)func main() {var kubeconfig *stringif home := homeDir(); home != "" {kubeconfig = flag.String("kubeconfig", filepath.Join(home, "src", "go-kubernetes", "config"), "(optional) absolute path to the kubeconfig file")} else {kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")}flag.Parse()// use the current context in kubeconfigconfig, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)if err != nil {panic(err.Error())}// create the clientsetclientset, err := kubernetes.NewForConfig(config)if err != nil {panic(err.Error())}for {pods, err := clientset.CoreV1().Pods("default").List(metav1.ListOptions{})if err != nil {panic(err.Error())}fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))// Examples for error handling:// - Use helper functions like e.g. errors.IsNotFound()// - And/or cast to StatusError and use its properties like e.g. ErrStatus.Messagenamespace := ""pod := "example-xxxxx"_, err = clientset.CoreV1().Pods(namespace).Get(pod, metav1.GetOptions{})if errors.IsNotFound(err) {fmt.Printf("Pod %s in namespace %s not found\n", pod, namespace)} else if statusError, isStatus := err.(*errors.StatusError); isStatus {fmt.Printf("Error getting pod %s in namespace %s: %v\n",pod, namespace, statusError.ErrStatus.Message)} else if err != nil {panic(err.Error())} else {fmt.Printf("Found pod %s in namespace %s\n", pod, namespace)}time.Sleep(10 * time.Second)}
}func homeDir() string {if h := os.Getenv("GOPATH"); h != "" {return h}return os.Getenv("USERPROFILE")
}
执行结果准确:
任何程序错误,以及技术疑问或需要解答的,请添加