2015-04-05 14:59:21 -07:00
|
|
|
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,
|
2015-04-05 22:48:39 -07:00
|
|
|
LogLevel: int(logging.INFO),
|
2015-04-05 14:59:21 -07:00
|
|
|
}
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
2015-04-05 22:48:39 -07:00
|
|
|
logs.Info("serving at: http://%s:%d/", hostname, config.Port)
|
2015-04-05 14:59:21 -07:00
|
|
|
|
|
|
|
addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
|
|
|
|
err = http.ListenAndServe(addr, sm)
|
|
|
|
if err != nil {
|
|
|
|
logs.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|