fork/gdu
git clone https://git.julia.blue/fork/gdu
d672bf4
subvolume
1package webui 2 3import ( 4"context" 5"errors" 6"fmt" 7"io" 8"net" 9"net/http" 10"os" 11"os/signal" 12"strings" 13"syscall" 14"time" 15 16 log"github.com/sirupsen/logrus" 17) 18 19// StartUILoop binds the listener, prints the URL, optionally opens the browser, 20// and serves the SPA and API until interrupted. It blocks, mirroring the other 21// frontends' StartUILoop contract. 22func (ui * UI )StartUILoop ()error { 23listener ,err := net .Listen ("tcp" ,ui .listenAddr ) 24if err != nil { 25return fmt .Errorf ("binding %s: %w" ,ui .listenAddr ,err ) 26 } 27 28url := "http://" + listener .Addr ().String () 29fmt .Fprintf (ui .output ,"Gdu web UI running at %s\n" ,url ) 30warnIfRemote (ui .output ,listener .Addr ()) 31 32if ui .openBrowser { 33if err := openBrowser (url ,ui .browserCmd );err != nil { 34log .Printf ("webui: could not open browser: %s" ,err ) 35fmt .Fprintf (ui .output ,"Open %s in your browser.\n" ,url ) 36 } 37 } 38 39srv := & http.Server { 40Handler :ui .routes (), 41ReadHeaderTimeout :10 * time .Second , 42 } 43 44shutdownDone := make (chan struct {}) 45go func () { 46sig := make (chan os.Signal ,1 ) 47signal .Notify (sig ,os .Interrupt ,syscall .SIGTERM ) 48<- sig 49ctx ,cancel := context .WithTimeout (context .Background (),5 * time .Second ) 50defer cancel () 51if err := srv .Shutdown (ctx );err != nil { 52log .Printf ("webui: shutdown: %s" ,err ) 53 } 54close (shutdownDone ) 55 }() 56 57err = srv .Serve (listener ) 58if errors .Is (err ,http .ErrServerClosed ) { 59<- shutdownDone 60return nil 61 } 62return err 63} 64 65// routes builds a dedicated mux (never the shared http.DefaultServeMux, which 66// is deliberately reset elsewhere to keep pprof handlers isolated). 67func (ui * UI )routes ()* http.ServeMux { 68mux := http .NewServeMux () 69mux .HandleFunc ("/api/v1/status" ,ui .handleStatus ) 70mux .HandleFunc ("/api/v1/nodes" ,ui .handleNodes ) 71mux .HandleFunc ("/api/v1/devices" ,ui .handleDevices ) 72mux .HandleFunc ("/api/v1/events" ,ui .handleEvents ) 73mux .Handle ("/" ,staticHandler ()) 74return mux 75} 76 77// warnIfRemote prints a security warning when the server is not bound to a 78// loopback address, since directory names and sizes can be sensitive. 79func warnIfRemote (w io.Writer ,addr net.Addr ) { 80host := addr .String () 81if i := strings .LastIndex (host ,":" );i >= 0 { 82host = host [:i ] 83 } 84ip := net .ParseIP (strings .Trim (host ,"[]" )) 85if ip != nil && ip .IsLoopback () { 86return 87 } 88fmt .Fprintln (w ,"WARNING: the web UI is reachable from other hosts on the network." ) 89fmt .Fprintln (w ," It exposes file names and sizes with no authentication." ) 90}