split web server into a listen and serve call

This commit is contained in:
sawka 2024-07-09 13:47:39 -07:00
parent f3b649aef1
commit fa3a670603
3 changed files with 22 additions and 14 deletions

View File

@ -9,9 +9,9 @@ import (
"log"
"os"
"os/signal"
"strconv"
"runtime"
"strconv"
"sync"
"syscall"
"time"
@ -119,10 +119,12 @@ func main() {
installShutdownSignalHandlers()
go stdinReadWatch()
configWatcher()
go web.RunWebSocketServer()
webListener, err := web.MakeTCPListener()
if err != nil {
log.Printf("error creating web listener: %v\n", err)
}
go func() {
time.Sleep(30 * time.Millisecond)
pidStr := os.Getenv(ReadySignalPidVarName)
if pidStr != "" {
_, err := strconv.Atoi(pidStr)
@ -132,6 +134,6 @@ func main() {
}
}
}()
web.RunWebServer() // blocking
web.RunWebServer(webListener) // blocking
runtime.KeepAlive(waveLock)
}

View File

@ -142,8 +142,6 @@ func (w *Watcher) sendInitialValues() error {
}
w.settingsData = message.Update
log.Printf("watcher: initial values: %s -> %v", filename, content)
return nil
}

View File

@ -10,6 +10,7 @@ import (
"io"
"io/fs"
"log"
"net"
"net/http"
"runtime/debug"
"strconv"
@ -211,29 +212,36 @@ func WebFnWrap(opts WebFnOpts, fn WebFnType) WebFnType {
}
}
func MakeTCPListener() (net.Listener, error) {
serverAddr := MainServerAddr
if wavebase.IsDevMode() {
serverAddr = MainServerDevAddr
}
rtn, err := net.Listen("tcp", serverAddr)
if err != nil {
return nil, fmt.Errorf("error creating listener at %v: %v", serverAddr, err)
}
log.Printf("Server listening on %s\n", serverAddr)
return rtn, nil
}
// blocking
// TODO: create listener separately and use http.Serve, so we can signal SIGUSR1 in a better way
func RunWebServer() {
func RunWebServer(listener net.Listener) {
gr := mux.NewRouter()
gr.HandleFunc("/wave/stream-file", WebFnWrap(WebFnOpts{AllowCaching: true}, handleStreamFile))
gr.HandleFunc("/wave/file", WebFnWrap(WebFnOpts{AllowCaching: false}, handleWaveFile))
gr.HandleFunc("/wave/service", WebFnWrap(WebFnOpts{JsonErrors: true}, handleService))
serverAddr := MainServerAddr
var allowedOrigins handlers.CORSOption
if wavebase.IsDevMode() {
log.Println("isDevMode")
serverAddr = MainServerDevAddr
allowedOrigins = handlers.AllowedOrigins([]string{"*"})
}
server := &http.Server{
Addr: serverAddr,
ReadTimeout: HttpReadTimeout,
WriteTimeout: HttpWriteTimeout,
MaxHeaderBytes: HttpMaxHeaderBytes,
Handler: handlers.CORS(allowedOrigins)(http.TimeoutHandler(gr, HttpTimeoutDuration, "Timeout")),
}
log.Printf("Running main server on %s\n", serverAddr)
err := server.ListenAndServe()
err := server.Serve(listener)
if err != nil {
log.Printf("ERROR: %v\n", err)
}