Created
August 14, 2023 02:22
-
-
Save clly/21e1c5c6bd3a41fd0232d17f0491e6c6 to your computer and use it in GitHub Desktop.
tshello
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
// The tshello server demonstrates how to use Tailscale as a library. | |
package main | |
import ( | |
"flag" | |
"fmt" | |
"html" | |
"log" | |
"net/http" | |
"strings" | |
"time" | |
"tailscale.com/tsnet" | |
) | |
var ( | |
addr = flag.String("addr", ":80", "address to listen on") | |
hostname = flag.String("hostname", "tshello", "hostname to use on the tailnet") | |
) | |
func main() { | |
flag.Parse() | |
s := new(tsnet.Server) | |
s.Hostname = *hostname | |
s.Ephemeral = true | |
fmt.Println(hostname) | |
defer s.Close() | |
ln, err := s.Listen("tcp", *addr) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer ln.Close() | |
lc, err := s.LocalClient() | |
if err != nil { | |
log.Fatal(err) | |
} | |
go func() { | |
log.Fatal(http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
who, err := lc.WhoIs(r.Context(), r.RemoteAddr) | |
if err != nil { | |
http.Error(w, err.Error(), 500) | |
return | |
} | |
fmt.Fprintf(w, "<html><body><h1>Hello, tailnet!</h1>\n") | |
fmt.Fprintf(w, "<p>You are <b>%s</b> from <b>%s</b> (%s)</p>", | |
html.EscapeString(who.UserProfile.LoginName), | |
html.EscapeString(firstLabel(who.Node.ComputedName)), | |
r.RemoteAddr) | |
}))) | |
}() | |
time.Sleep(time.Second * 10) | |
ln.Close() | |
s.Close() | |
} | |
func firstLabel(s string) string { | |
s, _, _ = strings.Cut(s, ".") | |
return s | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment