Use k8s port forwarding in current process

1/17/2019

I would like to port-forward a TCP connection to my program and use it to communicate with the pod. I am able to establish a connection to the pod and to execute a curl on http://localhost:9200/ from a different shell. However, when trying to reach the service from within my program, I am getting a connection refused.

Here is my snippet to establish the connection and make a local curl.

stopChan, readyChan := make(chan struct{}, 1), make(chan struct{}, 1)
out, errOut := new(bytes.Buffer), new(bytes.Buffer)
path := fmt.Sprintf("/api/v1/namespaces/%s/pods/%s/portforward", "default", "my-http-server")
hostIP := strings.TrimLeft(config.Host, "https://")
serverURL := url.URL{Scheme: "https", Path: path, Host: hostIP}

dialer := spdy.NewDialer(upgrader, &http.Client{Transport: roundTripper}, http.MethodGet, &serverURL)
forwarder, err := portforward.New(dialer, []string{flagPort}, stopChan, readyChan, out, errOut)
if err != nil {
    panic(err)
}

/* From here, I can make a curl to http://localhost:9200/ from a different shell */

/* But I can't curl from within this process */
resp, err := http.Get("http://localhost:9200/")
if err != nil {
    /* It is exiting here */
    panic(err)
}
fmt.Println(resp.Status, resp.Body)
defer resp.Body.Close()

I am getting: panic: dial tcp [::1]:9200: connect: connection refused

Should I reuse the dialer that I have setup to communicate with the pod? Ideally, I will need to reuse this connection with the Elasticsearch client Why do I get refused on both 127.0.0.1 and localhost as it is working fine outside of that process?

-- Arkon
elasticsearch
go
kubernetes
tcp

0 Answers