cmd/hello: refactor to use tsweb.Server.

Signed-off-by: David Anderson <danderson@tailscale.com>
This commit is contained in:
David Anderson
2022-02-03 14:17:32 -08:00
parent f13e5e38b2
commit 19b1c31e60

View File

@@ -18,10 +18,10 @@ import (
"net/http" "net/http"
"os" "os"
"strings" "strings"
"time"
"tailscale.com/client/tailscale" "tailscale.com/client/tailscale"
"tailscale.com/client/tailscale/apitype" "tailscale.com/client/tailscale/apitype"
"tailscale.com/tsweb"
) )
var ( var (
@@ -62,44 +62,37 @@ func main() {
http.HandleFunc("/", root) http.HandleFunc("/", root)
log.Printf("Starting hello server.") log.Printf("Starting hello server.")
errc := make(chan error, 1) mainAddr := *httpsAddr
if *httpAddr != "" { if mainAddr == "" {
log.Printf("running HTTP server on %s", *httpAddr) mainAddr = *httpAddr
go func() {
errc <- http.ListenAndServe(*httpAddr, nil)
}()
} }
if *httpsAddr != "" { httpCfg := tsweb.ServerConfig{
log.Printf("running HTTPS server on %s", *httpsAddr) Name: "hello",
go func() { Addr: mainAddr,
hs := &http.Server{ Handler: http.DefaultServeMux,
Addr: *httpsAddr, }
TLSConfig: &tls.Config{ server := tsweb.NewServer(httpCfg)
GetCertificate: func(hi *tls.ClientHelloInfo) (*tls.Certificate, error) { if server.HTTPS != nil {
switch hi.ServerName { server.HTTPS.TLSConfig.GetCertificate = func(hi *tls.ClientHelloInfo) (*tls.Certificate, error) {
case "hello.ts.net": switch hi.ServerName {
return tailscale.GetCertificate(hi) case "hello.ts.net":
case "hello.ipn.dev": return tailscale.GetCertificate(hi)
c, err := tls.LoadX509KeyPair( case "hello.ipn.dev":
"/etc/hello/hello.ipn.dev.crt", c, err := tls.LoadX509KeyPair(
"/etc/hello/hello.ipn.dev.key", "/etc/hello/hello.ipn.dev.crt",
) "/etc/hello/hello.ipn.dev.key",
if err != nil { )
return nil, err if err != nil {
} return nil, err
return &c, nil }
} return &c, nil
return nil, errors.New("invalid SNI name")
},
},
IdleTimeout: 30 * time.Second,
ReadHeaderTimeout: 20 * time.Second,
MaxHeaderBytes: 10 << 10,
} }
errc <- hs.ListenAndServeTLS("", "") return nil, errors.New("invalid SNI name")
}() }
}
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
} }
log.Fatal(<-errc)
} }
func devMode() bool { return *httpsAddr == "" && *httpAddr != "" } func devMode() bool { return *httpsAddr == "" && *httpAddr != "" }