feat: main.go - bootstrap from cold, SIGTERM flushes, listens :8310
This commit is contained in:
parent
fe371aef1e
commit
56563465a7
1 changed files with 32 additions and 19 deletions
51
main.go
51
main.go
|
|
@ -1,35 +1,48 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
_ "github.com/lib/pq"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
dsn := os.Getenv("POSTS_DSN")
|
s := NewStore()
|
||||||
if dsn == "" {
|
|
||||||
dsn = "postgres://posts:posts@127.0.0.1:5432/posts?sslmode=disable"
|
// Boot: restore from latest cold snapshot, if any.
|
||||||
|
if path := os.Getenv("POSTS_COLD_PATH"); path != "" {
|
||||||
|
s.flushPath = path
|
||||||
}
|
}
|
||||||
db, err := sql.Open("postgres", dsn)
|
if loaded, err := s.RestoreFromLatest(s.flushPath); err != nil {
|
||||||
if err != nil {
|
log.Fatalf("restore failed: %v", err)
|
||||||
log.Fatalf("open db: %v", err)
|
} else if loaded != "" {
|
||||||
}
|
log.Printf("restored from %s", loaded)
|
||||||
defer db.Close()
|
|
||||||
if err := db.Ping(); err != nil {
|
|
||||||
log.Fatalf("ping db: %v", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
srv := NewServer(db)
|
srv := NewServer(s)
|
||||||
addr := os.Getenv("ADDR")
|
|
||||||
if addr == "" {
|
// SIGTERM handler: cancel the flush context so the flush goroutine runs
|
||||||
addr = ":8310" // see go-htmx-web-dev port list: 8310 is next free
|
// its final flush before exit. Per Q6 D-cadence.
|
||||||
|
go func() {
|
||||||
|
sig := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
|
||||||
|
<-sig
|
||||||
|
log.Printf("shutdown signal received, flushing...")
|
||||||
|
ShutdownFlush()
|
||||||
|
if err := s.FlushNow(); err != nil {
|
||||||
|
log.Printf("final flush error: %v", err)
|
||||||
|
}
|
||||||
|
os.Exit(0)
|
||||||
|
}()
|
||||||
|
|
||||||
|
restAddr := os.Getenv("ADDR")
|
||||||
|
if restAddr == "" {
|
||||||
|
restAddr = ":8310"
|
||||||
}
|
}
|
||||||
log.Printf("posts listening on %s (dsn=%s)", addr, dsn)
|
log.Printf("posts listening on %s (cold=%s)", restAddr, s.flushPath)
|
||||||
if err := http.ListenAndServe(addr, srv.Routes()); err != nil {
|
if err := http.ListenAndServe(restAddr, srv.Routes()); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue