package cmd import ( "dev.sum7.eu/genofire/golang-lib/database" "dev.sum7.eu/genofire/golang-lib/file" "github.com/bdlm/log" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" "github.com/gin-contrib/static" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" "github.com/spf13/cobra" "golang.org/x/crypto/acme/autocert" "dev.sum7.eu/genofire/meetandeat/controller" "dev.sum7.eu/genofire/meetandeat/runtime" ) var configPath = "/etc/meetandeat.conf" type ServeConfig struct { RequestLog bool `toml:"request_log"` RequestLimit int `toml:"request_limit"` SessionSecret string `toml:"session_secret"` Listen string `toml:"listen"` Webroot string `toml:"webroot"` Database database.Config `toml:"database"` ACME struct { Enable bool `toml:"enable"` Domains []string `toml:"domains"` Cache string `toml:"cache"` } `toml:"acme"` } // serveCMD represents the query command var serveCMD = &cobra.Command{ Use: "serve ", Short: "run webserver", Example: `meetandeat serve "/etc/meetandeat.conf"`, Run: func(cmd *cobra.Command, args []string) { config := &ServeConfig{} if err := file.ReadTOML(configPath, config); err != nil { log.Panicf("open config file: %s", err) } if err := database.Open(config.Database); err != nil { log.Panicf("no database connection: %s", err) } gin.SetMode(gin.ReleaseMode) r := gin.New() if config.RequestLog { r.Use(gin.Logger()) log.Debug("request logging enabled") } r.Use(runtime.MaxAllowed(config.RequestLimit)) r.Use(gin.Recovery()) r.Use(sessions.Sessions("sid", cookie.NewStore([]byte(config.SessionSecret)))) controller.Bind(&r.RouterGroup) r.Use(static.Serve("/", static.LocalFile(config.Webroot, false))) if config.ACME.Enable { if config.Listen != "" { log.Panic("For ACME / Let's Encrypt it is not possible to set `listen`") } m := autocert.Manager{ Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(config.ACME.Domains...), Cache: autocert.DirCache(config.ACME.Cache), } log.Fatal(autotls.RunWithManager(r, &m)) } else { r.Run(config.Listen) } }, } func init() { serveCMD.PersistentFlags().StringVar(&configPath, "config", configPath, "path to config file") RootCMD.AddCommand(serveCMD) }