cadoles-profile/cmd/server/main.go

83 lines
1.9 KiB
Go
Raw Permalink Normal View History

2019-05-13 09:19:33 +02:00
package main
import (
"flag"
"log"
"net/http"
"os"
"forge.cadoles.com/Cadoles/cadoles-profile/cmd/server/config"
2019-05-13 09:19:33 +02:00
"forge.cadoles.com/wpetit/goweb/middleware/container"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/pkg/errors"
)
var (
configFile = ""
workdir = ""
dumpConfig = false
)
func init() {
flag.StringVar(&configFile, "config", configFile, "configuration file")
flag.StringVar(&workdir, "workdir", workdir, "working directory")
flag.BoolVar(&dumpConfig, "dump-config", dumpConfig, "dump configuration and exit")
}
func main() {
flag.Parse()
// Switch to new working directory if defined
if workdir != "" {
if err := os.Chdir(workdir); err != nil {
panic(errors.Wrapf(err, "error while changing working directory to '%s'", workdir))
}
}
// Load configuration file if defined, use default configuration otherwise
var conf *config.Config
var err error
if configFile != "" {
conf, err = config.NewFromFile(configFile)
if err != nil {
panic(errors.Wrapf(err, "error while loading config file '%s'", configFile))
}
} else {
conf = config.NewDefault()
}
// Dump configuration if asked
if dumpConfig {
if err := config.Dump(conf, os.Stdout); err != nil {
panic(errors.Wrap(err, "error while dumping config"))
}
os.Exit(0)
}
r := chi.NewRouter()
// Define base middlewares
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Create service container
ctn, err := getServiceContainer(conf)
if err != nil {
panic(errors.Wrap(err, "error while creating service container"))
}
// Expose service container on router
r.Use(container.ServiceContainer(ctn))
// Define routes
mountRoutes(r, conf)
log.Printf("listening on '%s'", conf.HTTP.Address)
if err := http.ListenAndServe(conf.HTTP.Address, r); err != nil {
panic(errors.Wrapf(err, "error while listening on '%s'", conf.HTTP.Address))
}
}