underbbs/underbbs.go

82 lines
1.4 KiB
Go

package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"time"
"forge.lightcrystal.systems/nilix/underbbs/cli"
"forge.lightcrystal.systems/nilix/underbbs/config"
"forge.lightcrystal.systems/nilix/underbbs/models"
"forge.lightcrystal.systems/nilix/underbbs/server"
)
func main() {
args := os.Args
var err error = nil
progname := filepath.Base(args[0])
cfg, err := config.LoadConfig()
if err != nil {
panic(err.Error())
}
switch progname {
case "underbbs-cli":
err = run_cli(cfg, args[1:]...)
default:
err = run_srvr(cfg)
}
if err != nil {
fmt.Println(err.Error())
}
}
func run_cli(settings models.GlobalSettings, args ...string) error {
return cli.Process(settings, args...)
}
func run_srvr(settings models.GlobalSettings) error {
l, err := net.Listen("tcp", ":"+strconv.FormatInt(int64(settings.Port), 10))
if err != nil {
return err
}
bbsServer := server.New(settings)
s := &http.Server{
Handler: bbsServer,
ReadTimeout: time.Second * 10,
WriteTimeout: time.Second * 10,
}
errc := make(chan error, 1)
go func() {
errc <- s.Serve(l)
}()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
select {
case err := <-errc:
log.Printf("failed to serve: %v", err)
case sig := <-sigs:
log.Printf("terminating: %v", sig)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
return s.Shutdown(ctx)
}