rogueserver/pokerogue-server.go

90 lines
1.9 KiB
Go
Raw Normal View History

2023-12-05 10:28:08 -08:00
package main
import (
"flag"
"log"
"net"
"net/http"
2023-12-28 17:01:55 -08:00
"os"
2024-04-17 16:31:12 -07:00
"os/signal"
"sync"
"syscall"
2023-12-05 10:28:08 -08:00
2024-04-14 16:25:36 -07:00
"github.com/pagefaultgames/pokerogue-server/api"
"github.com/pagefaultgames/pokerogue-server/db"
2023-12-05 10:28:08 -08:00
)
func main() {
2024-04-17 16:31:12 -07:00
// flag stuff
2023-12-29 11:30:47 -08:00
debug := flag.Bool("debug", false, "debug mode")
2023-12-28 19:08:50 -08:00
proto := flag.String("proto", "tcp", "protocol for api to use (tcp, unix)")
2023-12-28 19:16:47 -08:00
addr := flag.String("addr", "0.0.0.0", "network address for api to listen on")
2023-12-05 10:28:08 -08:00
dbuser := flag.String("dbuser", "pokerogue", "database username")
dbpass := flag.String("dbpass", "", "database password")
dbproto := flag.String("dbproto", "tcp", "protocol for database connection")
2023-12-28 19:18:57 -08:00
dbaddr := flag.String("dbaddr", "localhost", "database address")
2023-12-28 17:08:58 -08:00
dbname := flag.String("dbname", "pokeroguedb", "database name")
2023-12-05 10:28:08 -08:00
flag.Parse()
2024-04-17 16:31:12 -07:00
// get database connection
2023-12-05 10:28:08 -08:00
err := db.Init(*dbuser, *dbpass, *dbproto, *dbaddr, *dbname)
if err != nil {
log.Fatalf("failed to initialize database: %s", err)
}
2024-04-17 16:31:12 -07:00
// create listener
listener, err := createListener(*proto, *addr)
2023-12-05 10:28:08 -08:00
if err != nil {
log.Fatalf("failed to create net listener: %s", err)
}
2024-04-17 16:31:12 -07:00
// create exit handler
var exit sync.RWMutex
createExitHandler(&exit)
2023-12-28 17:06:06 -08:00
2024-04-17 16:31:12 -07:00
// init api
api.Init()
2024-03-16 18:51:13 -07:00
2024-04-17 16:31:12 -07:00
// start web server
err = http.Serve(listener, &api.Server{Debug: *debug, Exit: &exit})
2023-12-05 10:28:08 -08:00
if err != nil {
log.Fatalf("failed to create http server or server errored: %s", err)
}
}
2024-04-17 16:31:12 -07:00
func createListener(proto, addr string) (net.Listener, error) {
if proto == "unix" {
os.Remove(addr)
}
listener, err := net.Listen(proto, addr)
if err != nil {
return nil, err
}
if proto == "unix" {
os.Chmod(addr, 0777)
}
return listener, nil
}
func createExitHandler(mtx *sync.RWMutex) {
s := make(chan os.Signal, 1)
signal.Notify(s, syscall.SIGINT, syscall.SIGTERM)
go func() {
// wait for exit signal of some kind
<-s
// block new requests and wait for existing ones to finish
mtx.Lock()
// bail
os.Exit(0)
}()
}