serve.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package main
  2. import (
  3. "code.osinet.fr/fgm/kurz/web"
  4. "context"
  5. "database/sql"
  6. "github.com/spf13/viper"
  7. "log"
  8. "net/http"
  9. "os"
  10. "os/signal"
  11. "time"
  12. "code.osinet.fr/fgm/kurz/api"
  13. "code.osinet.fr/fgm/kurz/domain"
  14. "code.osinet.fr/fgm/kurz/infrastructure"
  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. router := mux.NewRouter()
  56. api.SetupRoutes(router)
  57. web.SetupRoutes(router)
  58. http.Handle("/", router)
  59. address := viper.Get("web.address").(string)
  60. // Start a server that can handle a SIGINT to shutdown.
  61. stop := make(chan os.Signal, 1)
  62. signal.Notify(stop, os.Interrupt)
  63. server := &http.Server{Addr: address, Handler: router}
  64. go func() {
  65. log.Printf("Listening on %s", address)
  66. err := server.ListenAndServe()
  67. log.Fatal(err)
  68. }()
  69. <-stop
  70. log.Println("Shutting down server")
  71. ctx, _ := context.WithTimeout(context.Background(), 1*time.Second)
  72. server.Shutdown(ctx)
  73. log.Println("Server gracefully stopped")
  74. }