Created
March 25, 2025 11:55
-
-
Save erdii/9562c2944abd4712868c677356b4f96a to your computer and use it in GitHub Desktop.
talk to an in-cluster http service by proxying via the apiserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"net/http" | |
"net/url" | |
"strings" | |
"k8s.io/client-go/rest" | |
"sigs.k8s.io/controller-runtime/pkg/client/config" | |
) | |
func must(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} | |
func main() { | |
restConfig := config.GetConfigOrDie() | |
transport, err := rest.TransportFor(restConfig) | |
must(err) | |
// Construct an http.Client that that authenticates with the apiserver. | |
client := &http.Client{ | |
Transport: transport, | |
} | |
// Construct request url: | |
host := restConfig.Host | |
if !strings.HasSuffix(host, "/") { | |
host = host + "/" | |
} | |
requestUrl, err := url.Parse(host) | |
must(err) | |
targetNamespace := "package-operator-system" | |
targetService := "package-operator-metrics" | |
targetPort := 8080 | |
targetPath := "/metrics" | |
requestUrl.Path = fmt.Sprintf( | |
"/api/v1/namespaces/%s/services/%s:%d/proxy%s", | |
targetNamespace, | |
targetService, | |
targetPort, | |
targetPath, | |
) | |
resp, err := client.Get(requestUrl.String()) | |
must(err) | |
defer resp.Body.Close() | |
body, err := io.ReadAll(resp.Body) | |
must(err) | |
fmt.Println(string(body)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Full blown port-forward alternative: https://microcumul.us/blog/k8s-port-forwarding/