happy/serve.go

89 lines
2.4 KiB
Go

package main
import (
"flag"
"os"
"strconv"
"code.chrissexton.org/cws/happy/web"
"code.chrissexton.org/cws/happy/db"
packr "github.com/gobuffalo/packr/v2"
"code.chrissexton.org/cws/happy/email"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
hashids "github.com/speps/go-hashids"
)
var (
dbPath = flag.String("db", "happy.db", "path to db")
httpAddr = flag.String("httpAddr", "0.0.0.0:8080", "http address")
salt = flag.String("salt", "happy", "salt for IDs")
minHashLen = flag.Int("minHashLen", 4, "minimum ID hash size")
develop = flag.Bool("develop", false, "turn on develop mode")
mailAddr = flag.String("mailAddr", "", "email server address")
mailPort = flag.Int("mailPort", 587, "email server port")
mailUser = flag.String("mailUser", "", "email user")
mailPass = flag.String("mailPass", "", "email password")
)
func validateMail() bool {
log.Debug().Str("mailAddr", *mailAddr).Msg("about to look up mail")
if val, ok := os.LookupEnv("MAIL_ADDR"); *mailAddr == "" && ok {
*mailAddr = val
log.Debug().Str("addr", *mailAddr).Str("val", val).Msg("set mailAddr")
}
if val, ok := os.LookupEnv("MAIL_PORT"); *mailPort == 0 && ok {
*mailPort, _ = strconv.Atoi(val)
log.Debug().Int("val", *mailPort).Msg("set mailPort")
}
if val, ok := os.LookupEnv("MAIL_USER"); *mailUser == "" && ok {
*mailUser = val
log.Debug().Str("val", *mailUser).Msg("set mailUser")
}
if val, ok := os.LookupEnv("MAIL_PASS"); *mailPass == "" && ok {
*mailPass = val
log.Debug().Str("val", *mailPass).Msg("set mailPass")
}
if *mailAddr != "" && *mailPort != 0 && *mailUser != "" && *mailPass != "" {
return true
}
return false
}
func main() {
flag.Parse()
log.Logger = log.Logger.Output(zerolog.ConsoleWriter{Out: os.Stderr})
zerolog.SetGlobalLevel(zerolog.DebugLevel)
box := packr.New("dist", "frontend/dist")
log.Debug().Strs("dirlist", box.List()).Msg("packr made")
db, err := db.New(*dbPath)
if err != nil {
log.Fatal().
Err(err).
Msg("could not connect to database")
}
hd := hashids.NewData()
hd.Salt = *salt
hd.MinLength = *minHashLen
h, _ := hashids.NewWithData(hd)
var mailClient *email.EMailClient
if validateMail() {
log.Debug().Msg("sending mail")
mailClient = email.New(*mailAddr, *mailPort, *mailUser, *mailPass)
} else {
log.Debug().Msg("mail disabled")
}
s := web.New(*httpAddr, "pub", db, *salt, h, box, mailClient)
s.Serve()
}