serve.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. cwd, err := os.Getwd()
  56. if err != nil {
  57. panic(err)
  58. }
  59. log.Printf("Server initializing in %s\n", cwd)
  60. // Set up globals from configuration, providing a few defaults.
  61. siteBaseURL := viper.Get("web.siteBaseUrl").(string)
  62. // This default is the relative position of the assets from the project root during development.
  63. viper.SetDefault("web.assetsPath", "web/public")
  64. assetsPath := viper.Get("web.assetsPath").(string)
  65. webConfig := viper.Get("web").(map[string]interface{})
  66. ui.SetupGlobals(webConfig)
  67. // Set up Web API and UI routes.
  68. router := mux.NewRouter()
  69. api.SetupRoutes(router)
  70. ui.SetupUI(router, assetsPath)
  71. http.Handle("/", router)
  72. // Start a server that can handle a SIGINT to shutdown.
  73. stop := make(chan os.Signal, 1)
  74. signal.Notify(stop, os.Interrupt)
  75. listenAddress := viper.Get("web.listenAddress").(string)
  76. server := &http.Server{Addr: listenAddress, Handler: router}
  77. go func() {
  78. log.Printf("Listening on %s, exposed as %s", listenAddress, siteBaseURL)
  79. err := server.ListenAndServe()
  80. log.Fatal(err)
  81. }()
  82. <-stop
  83. // Shutdown cleanly.
  84. log.Println("Shutting down server")
  85. ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
  86. server.Shutdown(ctx)
  87. log.Println("Server gracefully stopped")
  88. }