This commit is contained in:
mattliu007
2026-08-11 15:58:16 +08:00
committed by GitHub
parent 97e78943e6
commit d418b5a318
2 changed files with 53 additions and 2 deletions

View File

@@ -224,14 +224,24 @@ func createK8sClient(kubeConfig string) (*rest.RESTClient, error) {
return nil, err
}
// InClusterConfig does not set GroupVersion or NegotiatedSerializer,
// but both are required by rest.RESTClientFor.
// InClusterConfig does not set GroupVersion, NegotiatedSerializer or APIPath,
// but all of them are required by rest.RESTClientFor.
// Note that an empty APIPath makes every request target "/v1/namespaces/..."
// instead of "/api/v1/namespaces/...", which the API server rejects with
// 404 "the server could not find the requested resource".
if config.GroupVersion == nil {
config.GroupVersion = &schema.GroupVersion{Group: "", Version: "v1"}
}
if config.NegotiatedSerializer == nil {
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
}
if config.APIPath == "" {
if config.GroupVersion.Group == "" {
config.APIPath = "/api"
} else {
config.APIPath = "/apis"
}
}
client, err := rest.RESTClientFor(config)
if err != nil {

View File

@@ -0,0 +1,41 @@
package k8ssecret
import (
"strings"
"testing"
)
const testKubeConfig = `apiVersion: v1
kind: Config
clusters:
- name: test
cluster:
server: https://127.0.0.1:6443
insecure-skip-tls-verify: true
contexts:
- name: test
context:
cluster: test
user: test
current-context: test
users:
- name: test
user:
token: test-token
`
// Secrets live in the core API group, which is served under "/api".
// If APIPath is left empty, rest.RESTClientFor builds requests against
// "/v1/namespaces/..." and the API server answers 404
// ("the server could not find the requested resource").
func TestCreateK8sClientSetsCoreAPIPath(t *testing.T) {
client, err := createK8sClient(testKubeConfig)
if err != nil {
t.Fatalf("createK8sClient() returned an unexpected error: %v", err)
}
const want = "/api/v1"
if got := client.Get().URL().Path; !strings.HasPrefix(got, want) {
t.Errorf("request path = %q, want it to start with %q", got, want)
}
}