<p>For any example, the client-go connect to the kubernetes cluster with the kubeconfig file, but I don't want to do that. I've createed a service account, now I have a ServiceAccount Token, how to connect to the kubernetes cluster with this token outside of the kubernetes cluster?</p>
<pre><code>package main

import (
    &quot;flag&quot;
    &quot;k8s.io/client-go/tools/clientcmd&quot;
    &quot;log&quot;
    &quot;k8s.io/client-go/kubernetes&quot;
    metav1 &quot;k8s.io/apimachinery/pkg/apis/meta/v1&quot;
    &quot;fmt&quot;
)

var clientset *kubernetes.Clientset

func main()  {
    k8sconfig := flag.String(&quot;k8sconfig&quot;,&quot;./k8sconfig&quot;,&quot;kubernetes config file path&quot;)
    flag.Parse()
    config , err := clientcmd.BuildConfigFromFlags(&quot;&quot;,*k8sconfig)
    if err != nil {
        log.Println(err)
    }
    clientset , err = kubernetes.NewForConfig(config)
    if err != nil {
        log.Fatalln(err)
    } else {
        fmt.Println(&quot;connect k8s success&quot;)
    }


    pods,err := clientset.CoreV1().Pods(&quot;&quot;).List(metav1.ListOptions{})
    if err != nil {
        log.Println(err.Error())
    }
}
</code></pre>

yzhengwei
<p>The client-go already has built-in authentication both <strong>In Cluster Authentication</strong> (to be used from a Pod with a ServiceAccount) and also <strong>Out of Cluster Authentication</strong> (to be used from outside the cluster, e.g. for local development)</p>
<p>The client-go has examples of both:</p>
<ul>
<li><a href="https://github.com/kubernetes/client-go/blob/master/examples/out-of-cluster-client-configuration/main.go#L44-L62" rel="nofollow noreferrer">out of cluster authentication example</a></li>
<li><a href="https://github.com/kubernetes/client-go/blob/master/examples/in-cluster-client-configuration/main.go#L41-L50" rel="nofollow noreferrer">in cluster authentication example</a> - it is using ServiceAccount token</li>
</ul>
<p>The in-cluster exampe is quite short:</p>
<pre><code>    // creates the in-cluster config
    config, err := rest.InClusterConfig()
    if err != nil {
        panic(err.Error())
    }
    // creates the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }
</code></pre>
<p>You need to import <code>&quot;k8s.io/client-go/rest&quot;</code></p>
