<p>I am trying to get programmatically in Go, the namespace of the current-context from ~/.kube/config.</p>

<p>So far what I tried is from these modules:</p>

<pre><code>    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/kubernetes"



kubeconfig := filepath.Join(
     os.Getenv("HOME"), ".kube", "config",
)
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Namespace: %s\n", config.Namespace())
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
    log.Fatal(err)
}
</code></pre>

<p>But still no clue if clientset can give me the namespace I am looking for. From this thread:
<a href="https://stackoverflow.com/questions/53283347/how-to-get-current-namespace-of-an-in-cluster-go-kubernetes-client">How to get current namespace of an in-cluster go Kubernetes client</a></p>

<p>It says something of this to be done:
kubeconfig.Namespace()</p>

<p>I found a solution using <code>NewDefaultClientConfigLoadingRules</code> and then loading the rules. This works if your config is loadable with the default client config loading rules.</p>
<p>Example:</p>
<pre class="lang-golang prettyprint-override"><code>package main

import (
        &quot;github.com/davecgh/go-spew/spew&quot;
        &quot;k8s.io/client-go/tools/clientcmd&quot;
)

func main() {
        clientCfg, err := clientcmd.NewDefaultClientConfigLoadingRules().Load()
        spew.Dump(clientCfg, err)
}
</code></pre>
<p>Gives you a <a href="https://godoc.org/k8s.io/client-go/tools/clientcmd/api#Config" rel="nofollow noreferrer">https://godoc.org/k8s.io/client-go/tools/clientcmd/api#Config</a> which contains the current context including its namespace.</p>
<pre><code>Contexts: (map[string]*api.Context) (len=1) {
  (string) (len=17) &quot;xxx.xxxxx.xxx&quot;: (*api.Context)(0xc0001b2b40)({
   LocationOfOrigin: (string) (len=30) &quot;/path/to/.kube/config&quot;,
   Cluster: (string) (len=17) &quot;xxx.xxxxx.xxx&quot;,
   AuthInfo: (string) (len=29) &quot;xxxx@xxxx.com&quot;,
   Namespace: (string) (len=7) &quot;default&quot;,
   Extensions: (map[string]runtime.Object) {
   }
  })
 },
 CurrentContext: (string) (len=17) &quot;xxx.xxxxx.xxx&quot;,
</code></pre>
<p>For your information, <code>ClientConfigLoadingRules</code> is a structure with different properties to tell the client where to load the config from. The default one will use the path in your <code>KUBECONFIG</code> environment variable in the <code>Precedence</code> field.</p>
<pre><code>(*clientcmd.ClientConfigLoadingRules)(0xc0000a31d0)({
 ExplicitPath: (string) &quot;&quot;,
 Precedence: ([]string) (len=1 cap=1) {
  (string) (len=30) &quot;/path/to/.kube/config&quot;
 },
 MigrationRules: (map[string]string) (len=1) {
  (string) (len=30) &quot;/path/to/.kube/config&quot;: (string) (len=35) &quot;/path/to/.kube/.kubeconfig&quot;
 },
 DoNotResolvePaths: (bool) false,
 DefaultClientConfig: (clientcmd.ClientConfig) &lt;nil&gt;
})
</code></pre>
