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
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dsn := os.Getenv("POSTS_DSN")
|
||||
if dsn == "" {
|
||||
dsn = "postgres://posts:posts@127.0.0.1:5432/posts?sslmode=disable"
|
||||
s := NewStore()
|
||||
|
||||
// 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 err != nil {
|
||||
log.Fatalf("open db: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := db.Ping(); err != nil {
|
||||
log.Fatalf("ping db: %v", err)
|
||||
if loaded, err := s.RestoreFromLatest(s.flushPath); err != nil {
|
||||
log.Fatalf("restore failed: %v", err)
|
||||
} else if loaded != "" {
|
||||
log.Printf("restored from %s", loaded)
|
||||
}
|
||||
|
||||
srv := NewServer(db)
|
||||
addr := os.Getenv("ADDR")
|
||||
if addr == "" {
|
||||
addr = ":8310" // see go-htmx-web-dev port list: 8310 is next free
|
||||
srv := NewServer(s)
|
||||
|
||||
// SIGTERM handler: cancel the flush context so the flush goroutine runs
|
||||
// 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)
|
||||
}
|
||||
log.Printf("posts listening on %s (dsn=%s)", addr, dsn)
|
||||
if err := http.ListenAndServe(addr, srv.Routes()); err != nil {
|
||||
os.Exit(0)
|
||||
}()
|
||||
|
||||
restAddr := os.Getenv("ADDR")
|
||||
if restAddr == "" {
|
||||
restAddr = ":8310"
|
||||
}
|
||||
log.Printf("posts listening on %s (cold=%s)", restAddr, s.flushPath)
|
||||
if err := http.ListenAndServe(restAddr, srv.Routes()); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue