Skip to content

Commit

Permalink
fix: minor potential bug squash in the case that local addr is invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
jnsgruk committed Dec 15, 2023
1 parent 06f26d0 commit 77c21d6
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,52 +25,59 @@ var (
addr = flag.String("addr", ":8080", "the address to listen on in the case of a local listener")
)

// redirectToTLS is a simple http hander that redirects all HTTP requests to HTTPs.
func redirectToTLS(w http.ResponseWriter, r *http.Request) {
newURL := fmt.Sprintf("https://%s%s", r.Host, r.RequestURI)
http.Redirect(w, r, newURL, http.StatusMovedPermanently)
}

// serveLocal sets up a local TCP listener on the specified addr, and then serves the embedded
// filesystem over HTTP on the given listener.
func serveLocal(files fs.FS, addr string) {
var httpLn net.Listener
a, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
slog.Error(err.Error())
os.Exit(1)
}

if a, err := net.ResolveTCPAddr("tcp", addr); err == nil {
httpLn, err = net.ListenTCP("tcp", a)
if err != nil {
slog.Error(err.Error())
os.Exit(1)
}
httpLn, err := net.ListenTCP("tcp", a)
if err != nil {
slog.Error(err.Error())
os.Exit(1)
}

slog.Info(fmt.Sprintf("started HTTP listener on %s", addr))

// Serve an HTTP file server using our embedded filesystem
slog.Info("starting file server for web ui")
err := http.Serve(httpLn, http.FileServer(http.FS(files)))
err = http.Serve(httpLn, http.FileServer(http.FS(files)))
if err != nil {
slog.Error(err.Error())
os.Exit(1)
}
}

// serveTailscale sets up HTTP & HTTPs listeners on the tailnet and serves the embedded FS on them.
func serveTailscale(files fs.FS) {
tsLogger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{}))

s := &tsnet.Server{
tsnetServer := &tsnet.Server{
Hostname: *hostname,
Logf: func(msg string, args ...any) {
l := tsLogger.With(slog.String("source", "tsnet"), slog.String("hostname", *hostname))
l.Info(fmt.Sprintf(msg, args...))
},
}
defer s.Close()
defer tsnetServer.Close()

if !*tsnetLogs {
s.Logf = func(string, ...any) {}
tsnetServer.Logf = func(string, ...any) {}
slog.Warn("tsnet logs are disabled, interactive auth link will not be shown")
}

// Start a standard HTTP server in the background to redirect HTTP -> HTTPS
go func() {
httpLn, err := s.Listen("tcp", ":80")
httpLn, err := tsnetServer.Listen("tcp", ":80")
if err != nil {
slog.Error(err.Error())
os.Exit(1)
Expand All @@ -85,7 +92,7 @@ func serveTailscale(files fs.FS) {
}
}()

tlsLn, err := s.ListenTLS("tcp", ":443")
tlsLn, err := tsnetServer.ListenTLS("tcp", ":443")
if err != nil {
slog.Error(err.Error())
os.Exit(1)
Expand Down

0 comments on commit 77c21d6

Please sign in to comment.