control/controlclient: add a noiseClient.post helper method

In prep for a future change that would've been very copy/paste-y.

And because the set-dns call doesn't currently use a context,
so timeouts/cancelations are plumbed.

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:
Brad Fitzpatrick 2022-09-23 13:09:33 -07:00 committed by Brad Fitzpatrick
parent 8c72aabbdf
commit 6d04184325
2 changed files with 17 additions and 6 deletions

View File

@ -1434,15 +1434,11 @@ func (c *Direct) getNoiseClient() (*noiseClient, error) {
func (c *Direct) setDNSNoise(ctx context.Context, req *tailcfg.SetDNSRequest) error { func (c *Direct) setDNSNoise(ctx context.Context, req *tailcfg.SetDNSRequest) error {
newReq := *req newReq := *req
newReq.Version = tailcfg.CurrentCapabilityVersion newReq.Version = tailcfg.CurrentCapabilityVersion
np, err := c.getNoiseClient() nc, err := c.getNoiseClient()
if err != nil { if err != nil {
return err return err
} }
bodyData, err := json.Marshal(newReq) res, err := nc.post(ctx, "/machine/set-dns", req)
if err != nil {
return err
}
res, err := np.Post(fmt.Sprintf("https://%v/%v", np.host, "machine/set-dns"), "application/json", bytes.NewReader(bodyData))
if err != nil { if err != nil {
return err return err
} }

View File

@ -5,8 +5,10 @@
package controlclient package controlclient
import ( import (
"bytes"
"context" "context"
"crypto/tls" "crypto/tls"
"encoding/json"
"math" "math"
"net" "net"
"net/http" "net/http"
@ -228,3 +230,16 @@ func (nc *noiseClient) dial(_, _ string, _ *tls.Config) (net.Conn, error) {
mak.Set(&nc.connPool, ncc.id, ncc) mak.Set(&nc.connPool, ncc.id, ncc)
return ncc, nil return ncc, nil
} }
func (nc *noiseClient) post(ctx context.Context, path string, body any) (*http.Response, error) {
jbody, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", "https://"+nc.host+path, bytes.NewReader(jbody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return nc.Do(req)
}