From d1a5757639653ab88f1c5afef9223c3706ebd191 Mon Sep 17 00:00:00 2001 From: Xe Iaso Date: Thu, 8 Dec 2022 16:08:17 -0500 Subject: [PATCH] tsnet: add HTTP client method to tsnet.Server (#6669) This allows tsnet services to make requests to other services in the tailnet with the tsnet service identity instead of the identity of the host machine. This also enables tsnet services to make requests to other tailnet services without having to have the host machine join the tailnet. Signed-off-by: Xe Iaso Signed-off-by: Xe Iaso --- .../tsnet-http-client/tsnet-http-client.go | 45 +++++++++++++++++++ tsnet/tsnet.go | 12 +++++ 2 files changed, 57 insertions(+) create mode 100644 tsnet/example/tsnet-http-client/tsnet-http-client.go diff --git a/tsnet/example/tsnet-http-client/tsnet-http-client.go b/tsnet/example/tsnet-http-client/tsnet-http-client.go new file mode 100644 index 000000000..d707f73db --- /dev/null +++ b/tsnet/example/tsnet-http-client/tsnet-http-client.go @@ -0,0 +1,45 @@ +// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// The tshello server demonstrates how to use Tailscale as a library. +package main + +import ( + "flag" + "fmt" + "log" + "os" + "path/filepath" + + "tailscale.com/tsnet" +) + +func main() { + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "Usage: %s \n", filepath.Base(os.Args[0])) + os.Exit(2) + } + flag.Parse() + + if flag.NArg() != 1 { + flag.Usage() + } + tailnetURL := flag.Arg(0) + + s := new(tsnet.Server) + defer s.Close() + + if err := s.Start(); err != nil { + log.Fatal(err) + } + + cli := s.HTTPClient() + + resp, err := cli.Get(tailnetURL) + if err != nil { + log.Fatal(err) + } + + resp.Write(os.Stdout) +} diff --git a/tsnet/tsnet.go b/tsnet/tsnet.go index ca6bf81f9..c06555bd7 100644 --- a/tsnet/tsnet.go +++ b/tsnet/tsnet.go @@ -116,6 +116,18 @@ func (s *Server) Dial(ctx context.Context, network, address string) (net.Conn, e return s.dialer.UserDial(ctx, network, address) } +// HTTPClient returns an HTTP client that is configured to connect over Tailscale. +// +// This is useful if you need to have your tsnet services connect to other devices on +// your tailnet. +func (s *Server) HTTPClient() *http.Client { + return &http.Client { + Transport: &http.Transport { + DialContext: s.Dial, + }, + } +} + // LocalClient returns a LocalClient that speaks to s. // // It will start the server if it has not been started yet. If the server's