2021-05-14 15:53:55 +00:00
|
|
|
// 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 (
|
2021-10-12 04:17:19 +00:00
|
|
|
"crypto/tls"
|
|
|
|
"flag"
|
2021-05-14 15:53:55 +00:00
|
|
|
"fmt"
|
|
|
|
"html"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"tailscale.com/tsnet"
|
|
|
|
)
|
|
|
|
|
2021-10-12 04:17:19 +00:00
|
|
|
var (
|
|
|
|
addr = flag.String("addr", ":80", "address to listen on")
|
|
|
|
)
|
|
|
|
|
2021-05-14 15:53:55 +00:00
|
|
|
func main() {
|
2021-10-12 04:17:19 +00:00
|
|
|
flag.Parse()
|
2021-05-14 15:53:55 +00:00
|
|
|
s := new(tsnet.Server)
|
2022-09-26 22:37:27 +00:00
|
|
|
defer s.Close()
|
2021-10-12 04:17:19 +00:00
|
|
|
ln, err := s.Listen("tcp", *addr)
|
2021-05-14 15:53:55 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2022-09-26 22:37:27 +00:00
|
|
|
defer ln.Close()
|
|
|
|
|
2022-10-17 17:43:46 +00:00
|
|
|
lc, err := s.LocalClient()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2021-10-12 04:17:19 +00:00
|
|
|
if *addr == ":443" {
|
|
|
|
ln = tls.NewListener(ln, &tls.Config{
|
2022-11-25 09:55:05 +00:00
|
|
|
GetCertificate: lc.GetCertificate,
|
2021-10-12 04:17:19 +00:00
|
|
|
})
|
|
|
|
}
|
2021-05-14 15:53:55 +00:00
|
|
|
log.Fatal(http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2022-10-17 17:43:46 +00:00
|
|
|
who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
|
2021-10-06 04:40:19 +00:00
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), 500)
|
2021-05-14 15:53:55 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
fmt.Fprintf(w, "<html><body><h1>Hello, world!</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)
|
|
|
|
})))
|
|
|
|
}
|
|
|
|
|
|
|
|
func firstLabel(s string) string {
|
2022-11-07 20:06:34 +00:00
|
|
|
s, _, _ = strings.Cut(s, ".")
|
2021-05-14 15:53:55 +00:00
|
|
|
return s
|
|
|
|
}
|