chore(project): bootstrap project tree
This commit is contained in:
100
cmd/server/container.go
Normal file
100
cmd/server/container.go
Normal file
@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/wader/gormstore"
|
||||
|
||||
"forge.cadoles.com/Cadoles/guesstimate/internal/orm"
|
||||
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
|
||||
"forge.cadoles.com/Cadoles/guesstimate/internal/config"
|
||||
oidc "forge.cadoles.com/wpetit/goweb-oidc"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
"gitlab.com/wpetit/goweb/service/build"
|
||||
"gitlab.com/wpetit/goweb/service/session"
|
||||
"gitlab.com/wpetit/goweb/session/gorilla"
|
||||
)
|
||||
|
||||
func getServiceContainer(ctx context.Context, conf *config.Config) (*service.Container, error) {
|
||||
// Initialize and configure service container
|
||||
ctn := service.NewContainer()
|
||||
|
||||
ctn.Provide(build.ServiceName, build.ServiceProvider(ProjectVersion, GitRef, BuildDate))
|
||||
|
||||
// Generate random cookie authentication key if none is set
|
||||
if conf.HTTP.CookieAuthenticationKey == "" {
|
||||
logger.Info(ctx, "could not find cookie authentication key. generating one...")
|
||||
|
||||
cookieAuthenticationKey, err := gorilla.GenerateRandomBytes(64)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not generate cookie authentication key")
|
||||
}
|
||||
|
||||
conf.HTTP.CookieAuthenticationKey = string(cookieAuthenticationKey)
|
||||
}
|
||||
|
||||
// Generate random cookie encryption key if none is set
|
||||
if conf.HTTP.CookieEncryptionKey == "" {
|
||||
logger.Info(ctx, "could not find cookie encryption key. generating one...")
|
||||
|
||||
cookieEncryptionKey, err := gorilla.GenerateRandomBytes(32)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not generate cookie encryption key")
|
||||
}
|
||||
|
||||
conf.HTTP.CookieEncryptionKey = string(cookieEncryptionKey)
|
||||
}
|
||||
|
||||
ctn.Provide(orm.ServiceName, orm.ServiceProvider("postgres", conf.Database.DSN, conf.Debug))
|
||||
|
||||
orm, err := orm.From(ctn)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
// Create and initialize HTTP session service provider
|
||||
sessionStore := gormstore.NewOptions(
|
||||
orm.DB(),
|
||||
gormstore.Options{
|
||||
TableName: "sessions",
|
||||
SkipCreateTable: false,
|
||||
},
|
||||
[]byte(conf.HTTP.CookieAuthenticationKey),
|
||||
[]byte(conf.HTTP.CookieEncryptionKey),
|
||||
)
|
||||
|
||||
quit := make(chan struct{})
|
||||
go sessionStore.PeriodicCleanup(1*time.Hour, quit)
|
||||
|
||||
// Define default cookie options
|
||||
sessionStore.SessionOpts.Path = "/"
|
||||
sessionStore.SessionOpts.HttpOnly = true
|
||||
sessionStore.SessionOpts.MaxAge = conf.HTTP.CookieMaxAge
|
||||
sessionStore.SessionOpts.SameSite = http.SameSiteStrictMode
|
||||
|
||||
ctn.Provide(
|
||||
session.ServiceName,
|
||||
gorilla.ServiceProvider("guesstimate", sessionStore),
|
||||
)
|
||||
|
||||
// Create and expose config service provider
|
||||
ctn.Provide(config.ServiceName, config.ServiceProvider(conf))
|
||||
|
||||
provider, err := oidc.NewProvider(ctx, conf.OIDC.IssuerURL)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not create oidc provider")
|
||||
}
|
||||
|
||||
ctn.Provide(oidc.ServiceName, oidc.ServiceProvider(
|
||||
oidc.WithCredentials(conf.OIDC.ClientID, conf.OIDC.ClientSecret),
|
||||
oidc.WithProvider(provider),
|
||||
oidc.WithScopes("email", "openid"),
|
||||
))
|
||||
|
||||
return ctn, nil
|
||||
}
|
183
cmd/server/main.go
Normal file
183
cmd/server/main.go
Normal file
@ -0,0 +1,183 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/Cadoles/guesstimate/internal/config"
|
||||
"forge.cadoles.com/Cadoles/guesstimate/internal/route"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"os"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
)
|
||||
|
||||
//nolint: gochecknoglobals
|
||||
var (
|
||||
configFile = ""
|
||||
workdir = ""
|
||||
dumpConfig = false
|
||||
version = false
|
||||
migrate = ""
|
||||
)
|
||||
|
||||
// nolint: gochecknoglobals
|
||||
var (
|
||||
GitRef = "unknown"
|
||||
ProjectVersion = "unknown"
|
||||
BuildDate = "unknown"
|
||||
)
|
||||
|
||||
//nolint: gochecknoinits
|
||||
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")
|
||||
flag.BoolVar(&version, "version", version, "show version and exit")
|
||||
flag.StringVar(&migrate, "migrate", migrate, "migrate data schema version and exit, possible values: latest, down, up")
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
|
||||
flag.Parse()
|
||||
|
||||
if version {
|
||||
fmt.Printf("%s (%s) - %s\n", ProjectVersion, GitRef, BuildDate)
|
||||
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
// Switch to new working directory if defined
|
||||
if workdir != "" {
|
||||
if err := os.Chdir(workdir); err != nil {
|
||||
logger.Fatal(
|
||||
ctx,
|
||||
"could not change working directory",
|
||||
logger.E(err),
|
||||
logger.F("workdir", 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 {
|
||||
log.Fatalf("%+v", errors.Wrapf(err, " '%s'", configFile))
|
||||
logger.Fatal(
|
||||
ctx,
|
||||
"could not load config file",
|
||||
logger.E(err),
|
||||
logger.F("configFile", configFile),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if dumpConfig {
|
||||
conf = config.NewDumpDefault()
|
||||
} else {
|
||||
conf = config.NewDefault()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Dump configuration if asked
|
||||
if dumpConfig {
|
||||
if err := config.Dump(conf, os.Stdout); err != nil {
|
||||
logger.Fatal(
|
||||
ctx,
|
||||
"could not dump config",
|
||||
logger.E(err),
|
||||
)
|
||||
}
|
||||
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
if err := config.WithEnvironment(conf); err != nil {
|
||||
logger.Fatal(
|
||||
ctx,
|
||||
"could not override config with environment",
|
||||
logger.E(err),
|
||||
)
|
||||
}
|
||||
|
||||
logger.Info(
|
||||
ctx,
|
||||
"starting",
|
||||
logger.F("gitRef", GitRef),
|
||||
logger.F("projectVersion", ProjectVersion),
|
||||
logger.F("buildDate", BuildDate),
|
||||
)
|
||||
|
||||
logger.Debug(ctx, "setting log format", logger.F("format", conf.Log.Format))
|
||||
logger.SetFormat(conf.Log.Format)
|
||||
|
||||
logger.Debug(ctx, "setting log level", logger.F("level", conf.Log.Level.String()))
|
||||
logger.SetLevel(conf.Log.Level)
|
||||
|
||||
// Create service container
|
||||
ctn, err := getServiceContainer(ctx, conf)
|
||||
if err != nil {
|
||||
logger.Fatal(
|
||||
ctx,
|
||||
"could not create service container",
|
||||
logger.E(err),
|
||||
)
|
||||
}
|
||||
|
||||
ctx = container.WithContainer(ctx, ctn)
|
||||
|
||||
if migrate != "" {
|
||||
if err := applyMigration(ctx, ctn); err != nil {
|
||||
logger.Fatal(
|
||||
ctx,
|
||||
"could not apply migration",
|
||||
logger.E(err),
|
||||
)
|
||||
}
|
||||
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
r := chi.NewRouter()
|
||||
|
||||
// Define base middlewares
|
||||
r.Use(middleware.Logger)
|
||||
r.Use(middleware.Recoverer)
|
||||
|
||||
// Expose service container on router
|
||||
r.Use(container.ServiceContainer(ctn))
|
||||
|
||||
// Define routes
|
||||
if err := route.Mount(r, conf); err != nil {
|
||||
logger.Fatal(
|
||||
ctx,
|
||||
"could not mount http routes",
|
||||
logger.E(err),
|
||||
)
|
||||
}
|
||||
|
||||
logger.Info(ctx, "listening", logger.F("address", conf.HTTP.Address))
|
||||
if err := http.ListenAndServe(conf.HTTP.Address, r); err != nil {
|
||||
logger.Fatal(
|
||||
ctx,
|
||||
"could not listen",
|
||||
logger.E(err),
|
||||
logger.F("address", conf.HTTP.Address),
|
||||
)
|
||||
}
|
||||
}
|
106
cmd/server/migration.go
Normal file
106
cmd/server/migration.go
Normal file
@ -0,0 +1,106 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"forge.cadoles.com/Cadoles/guesstimate/internal/model"
|
||||
"forge.cadoles.com/Cadoles/guesstimate/internal/orm"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
)
|
||||
|
||||
const (
|
||||
migrateUp = "up"
|
||||
migrateLatest = "latest"
|
||||
migrateDown = "down"
|
||||
)
|
||||
|
||||
func applyMigration(ctx context.Context, ctn *service.Container) error {
|
||||
orm, err := orm.From(ctn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
migr := orm.Migration()
|
||||
|
||||
// Register available migrations
|
||||
migr.Register(
|
||||
m000initialSchema(),
|
||||
)
|
||||
|
||||
currentVersion, err := migr.CurrentVersion(ctx)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not retrieve current data schema version")
|
||||
}
|
||||
|
||||
switch migrate {
|
||||
case migrateUp:
|
||||
if err := migr.Up(ctx); err != nil {
|
||||
return errors.Wrap(err, "could not apply up migration")
|
||||
}
|
||||
|
||||
case migrateLatest:
|
||||
latestVersion, err := migr.LatestVersion()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not retrieve latest data schema version")
|
||||
}
|
||||
|
||||
logger.Info(
|
||||
ctx,
|
||||
"migrating data schema to latest version",
|
||||
logger.F("currentVersion", currentVersion),
|
||||
logger.F("latestVersion", latestVersion),
|
||||
)
|
||||
|
||||
// Execute migration to latest available version
|
||||
if err := migr.Latest(ctx); err != nil {
|
||||
return errors.Wrap(err, "could not migrate to latest data schema")
|
||||
}
|
||||
|
||||
case migrateDown:
|
||||
if err := migr.Down(ctx); err != nil {
|
||||
return errors.Wrap(err, "could not apply down migration")
|
||||
}
|
||||
|
||||
default:
|
||||
return errors.Errorf("unknown migration command: '%s'", migrate)
|
||||
}
|
||||
|
||||
logger.Info(
|
||||
ctx,
|
||||
"migration completed",
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// nolint: gochecknoglobals
|
||||
var initialModels = []interface{}{
|
||||
&model.User{},
|
||||
}
|
||||
|
||||
func m000initialSchema() orm.Migration {
|
||||
return orm.NewDBMigration(
|
||||
"00_initial_schema",
|
||||
func(ctx context.Context, tx *gorm.DB) error {
|
||||
for _, m := range initialModels {
|
||||
if err := tx.AutoMigrate(m).Error; err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
func(ctx context.Context, tx *gorm.DB) error {
|
||||
for _, m := range initialModels {
|
||||
if err := tx.DropTableIfExists(m).Error; err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
)
|
||||
}
|
Reference in New Issue
Block a user