76 lines
1.4 KiB
Go
76 lines
1.4 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"os/signal"
|
||
|
|
||
|
"mcquay.me/chat"
|
||
|
|
||
|
"github.com/kelseyhightower/envconfig"
|
||
|
"github.com/op/go-logging"
|
||
|
)
|
||
|
|
||
|
const usage = "chatd"
|
||
|
|
||
|
type Config struct {
|
||
|
Host string
|
||
|
Port int
|
||
|
Static string
|
||
|
LogLevel int
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
config := &Config{
|
||
|
Host: "",
|
||
|
Port: 8000,
|
||
|
LogLevel: int(logging.DEBUG),
|
||
|
}
|
||
|
err := envconfig.Process("chat", config)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
format := logging.MustStringFormatter(chat.Format)
|
||
|
be := logging.NewLogBackend(os.Stderr, "", 0)
|
||
|
bef := logging.NewBackendFormatter(be, format)
|
||
|
bel := logging.AddModuleLevel(bef)
|
||
|
bel.SetLevel(logging.Level(config.LogLevel), "")
|
||
|
logging.SetBackend(bel)
|
||
|
logs := logging.MustGetLogger("root")
|
||
|
|
||
|
sigs := make(chan os.Signal, 1)
|
||
|
signal.Notify(sigs, os.Interrupt, os.Kill)
|
||
|
go func() {
|
||
|
s := <-sigs
|
||
|
logs.Fatalf("signal: %+v", s)
|
||
|
os.Exit(1)
|
||
|
}()
|
||
|
|
||
|
sm := http.NewServeMux()
|
||
|
_, err = chat.NewChat(
|
||
|
sm,
|
||
|
config.Static,
|
||
|
)
|
||
|
if err != nil {
|
||
|
logs.Fatalf("problem initializing chat server: %+v", err)
|
||
|
}
|
||
|
|
||
|
hostname := "localhost"
|
||
|
if config.Host == "" {
|
||
|
hostname, err = os.Hostname()
|
||
|
if err != nil {
|
||
|
logs.Fatal("problem getting hostname:", err)
|
||
|
}
|
||
|
}
|
||
|
logs.Debug("serving at: http://%s:%d/", hostname, config.Port)
|
||
|
|
||
|
addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
|
||
|
err = http.ListenAndServe(addr, sm)
|
||
|
if err != nil {
|
||
|
logs.Fatal(err)
|
||
|
}
|
||
|
}
|