Skip to content

Instantly share code, notes, and snippets.

@erdii
Created March 25, 2025 11:55
Show Gist options
  • Save erdii/9562c2944abd4712868c677356b4f96a to your computer and use it in GitHub Desktop.
Save erdii/9562c2944abd4712868c677356b4f96a to your computer and use it in GitHub Desktop.
talk to an in-cluster http service by proxying via the apiserver
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))
}
@erdii
Copy link
Author

erdii commented Mar 25, 2025

Full blown port-forward alternative: https://microcumul.us/blog/k8s-port-forwarding/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment