|
@@ -1,16 +1,62 @@
|
|
|
package main
|
|
|
|
|
|
import (
|
|
|
+ "code.osinet.fr/fgm/kurz/api"
|
|
|
+ "code.osinet.fr/fgm/kurz/domain"
|
|
|
+ "code.osinet.fr/fgm/kurz/infrastructure"
|
|
|
+ "database/sql"
|
|
|
"github.com/spf13/cobra"
|
|
|
+ "github.com/spf13/viper"
|
|
|
+ "log"
|
|
|
)
|
|
|
|
|
|
var cmdServe = &cobra.Command{
|
|
|
Args: cobra.NoArgs,
|
|
|
Long: "Start HTTP Server",
|
|
|
+ Run: serveMarkupHandler,
|
|
|
Short: "Top-level command for HTTP Serving.",
|
|
|
Use: "serve",
|
|
|
}
|
|
|
|
|
|
+// db is the database connection shared by "serve *" commands.
|
|
|
+var db *sql.DB
|
|
|
+
|
|
|
func init() {
|
|
|
cmd.AddCommand(cmdServe)
|
|
|
}
|
|
|
+
|
|
|
+func ensureInfrastructure(db *sql.DB) *sql.DB {
|
|
|
+ if db != nil {
|
|
|
+ err := db.Ping()
|
|
|
+ if err != nil {
|
|
|
+ db = nil
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ if db != nil {
|
|
|
+ return db
|
|
|
+ }
|
|
|
+
|
|
|
+ dbDriver, dbDsn := infrastructure.ParseDbCred()
|
|
|
+ db, err := infrastructure.DbDial(dbDriver, dbDsn)
|
|
|
+ if err != nil {
|
|
|
+ panic(err)
|
|
|
+ }
|
|
|
+
|
|
|
+ domain.RegisterRepositories(
|
|
|
+ infrastructure.MySQLShortURLRepository{DB: db},
|
|
|
+ infrastructure.MySQLTargetURLRepository{DB: db},
|
|
|
+ )
|
|
|
+
|
|
|
+ return db
|
|
|
+}
|
|
|
+
|
|
|
+// serveMarkupHandler handles paths below /web/public.
|
|
|
+func serveMarkupHandler(_ *cobra.Command, args []string) {
|
|
|
+ db = ensureInfrastructure(db)
|
|
|
+ defer db.Close()
|
|
|
+
|
|
|
+ address := viper.Get("web.address").(string)
|
|
|
+ err := api.ListenAndServe(address)
|
|
|
+ log.Fatal(err)
|
|
|
+}
|