happy/serve.go

89 lines
2.4 KiB
Go
Raw Normal View History

2019-10-15 21:17:07 +00:00
package main
import (
2019-10-18 12:46:20 +00:00
"flag"
2019-10-15 21:17:07 +00:00
"os"
2019-10-29 04:52:11 +00:00
"strconv"
"code.chrissexton.org/cws/happy/web"
"code.chrissexton.org/cws/happy/db"
2019-10-15 21:17:07 +00:00
2019-10-29 04:52:11 +00:00
packr "github.com/gobuffalo/packr/v2"
"code.chrissexton.org/cws/happy/email"
_ "github.com/mattn/go-sqlite3"
2019-10-15 21:17:07 +00:00
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
2019-10-28 14:35:14 +00:00
hashids "github.com/speps/go-hashids"
2019-10-15 21:17:07 +00:00
)
2019-10-18 12:46:20 +00:00
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")
2019-10-29 04:52:11 +00:00
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")
2019-10-18 12:46:20 +00:00
)
2019-10-29 04:52:11 +00:00
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
}
2019-10-15 21:17:07 +00:00
func main() {
2019-10-18 12:46:20 +00:00
flag.Parse()
2019-10-15 21:17:07 +00:00
log.Logger = log.Logger.Output(zerolog.ConsoleWriter{Out: os.Stderr})
zerolog.SetGlobalLevel(zerolog.DebugLevel)
2019-10-28 14:35:14 +00:00
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
2019-10-29 04:52:11 +00:00
if validateMail() {
log.Debug().Msg("sending mail")
mailClient = email.New(*mailAddr, *mailPort, *mailUser, *mailPass)
2019-10-29 04:52:11 +00:00
} else {
log.Debug().Msg("mail disabled")
}
s := web.New(*httpAddr, "pub", db, *salt, h, box, mailClient)
s.Serve()
2019-10-15 21:17:07 +00:00
}