github.com/oam-dev/cluster-gateway@v1.9.0/pkg/util/namespace.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  )
     8  
     9  const inClusterNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
    10  
    11  func GetInClusterNamespace() (string, error) {
    12  	// Check whether the namespace file exists.
    13  	// If not, we are not running in cluster so can't guess the namespace.
    14  	if _, err := os.Stat(inClusterNamespacePath); os.IsNotExist(err) {
    15  		return "", fmt.Errorf("not running in-cluster, please specify LeaderElectionNamespace")
    16  	} else if err != nil {
    17  		return "", fmt.Errorf("error checking namespace file: %w", err)
    18  	}
    19  
    20  	// Load the namespace file and return its content
    21  	namespace, err := ioutil.ReadFile(inClusterNamespacePath)
    22  	if err != nil {
    23  		return "", fmt.Errorf("error reading namespace file: %w", err)
    24  	}
    25  	return string(namespace), nil
    26  }