serve.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package main
  2. import (
  3. "context"
  4. "database/sql"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "time"
  10. "code.osinet.fr/fgm/kurz/web/ui"
  11. "github.com/spf13/viper"
  12. "code.osinet.fr/fgm/kurz/domain"
  13. "code.osinet.fr/fgm/kurz/infrastructure"
  14. "code.osinet.fr/fgm/kurz/web/api"
  15. "github.com/gorilla/mux"
  16. "github.com/spf13/cobra"
  17. )
  18. var cmdServe = &cobra.Command{
  19. Args: cobra.NoArgs,
  20. Long: "Start HTTP Server",
  21. Run: serveHandler,
  22. Short: "Top-level command for HTTP Serving.",
  23. Use: "serve",
  24. }
  25. // db is the database connection shared by "serve *" commands.
  26. var db *sql.DB
  27. func init() {
  28. cmd.AddCommand(cmdServe)
  29. }
  30. func ensureInfrastructure(db *sql.DB) *sql.DB {
  31. if db != nil {
  32. err := db.Ping()
  33. if err != nil {
  34. db = nil
  35. }
  36. }
  37. if db != nil {
  38. return db
  39. }
  40. dbDriver, dbDsn := infrastructure.ParseDbCred()
  41. db, err := infrastructure.DbDial(dbDriver, dbDsn)
  42. if err != nil {
  43. panic(err)
  44. }
  45. domain.RegisterRepositories(
  46. infrastructure.MySQLShortURLRepository{DB: db},
  47. infrastructure.MySQLTargetURLRepository{DB: db},
  48. )
  49. return db
  50. }
  51. // serveHandler handles Web paths.
  52. func serveHandler(_ *cobra.Command, args []string) {
  53. db = ensureInfrastructure(db)
  54. defer db.Close()
  55. // Set up globals from configuration, providing a few defaults.
  56. siteBaseURL := viper.Get("web.siteBaseUrl").(string)
  57. // This default is the relative position of the assets from the project root during development.
  58. viper.SetDefault("web.assetsPath", "web/ui/public")
  59. assetsPath := viper.Get("web.assetsPath").(string)
  60. webConfig := viper.Get("web").(map[string]interface{})
  61. ui.SetupGlobals(webConfig)
  62. // Set up Web API and UI routes.
  63. router := mux.NewRouter()
  64. api.SetupRoutes(router)
  65. ui.SetupUI(router, assetsPath)
  66. http.Handle("/", router)
  67. // Start a server that can handle a SIGINT to shutdown.
  68. stop := make(chan os.Signal, 1)
  69. signal.Notify(stop, os.Interrupt)
  70. listenAddress := viper.Get("web.listenAddress").(string)
  71. server := &http.Server{Addr: listenAddress, Handler: router}
  72. go func() {
  73. log.Printf("Listening on %s, exposed as %s", listenAddress, siteBaseURL)
  74. err := server.ListenAndServe()
  75. log.Fatal(err)
  76. }()
  77. <-stop
  78. // Shutdown cleanly.
  79. log.Println("Shutting down server")
  80. ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
  81. server.Shutdown(ctx)
  82. log.Println("Server gracefully stopped")
  83. }