github.com/dimeko/sapi@v0.0.0-20231115204413-952501e4268a/cmd/server.go (about)

     1  package cmd
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  	"net/http"
     7  	"os"
     8  	"os/signal"
     9  	"path/filepath"
    10  	"syscall"
    11  	"time"
    12  
    13  	"github.com/dimeko/sapi/api"
    14  	"github.com/dimeko/sapi/app"
    15  	"github.com/joho/godotenv"
    16  	"github.com/spf13/cobra"
    17  )
    18  
    19  var srvCmd = &cobra.Command{
    20  	Use:   "server",
    21  	Short: "Starting server",
    22  	Run:   start,
    23  }
    24  
    25  func init() {
    26  	rootCmd.AddCommand(srvCmd)
    27  }
    28  
    29  func start(command *cobra.Command, args []string) {
    30  	StartServer()
    31  }
    32  
    33  func StartServer() {
    34  	err := godotenv.Load(filepath.Join("./", ".env"))
    35  	if err != nil {
    36  		panic("Cannot find .env file")
    37  	}
    38  
    39  	port := os.Getenv("APP_PORT")
    40  	app := app.New()
    41  	api := api.New(app)
    42  	httpServer := &http.Server{
    43  		Handler:      api.Router,
    44  		Addr:         ":" + port,
    45  		WriteTimeout: 15 * time.Second,
    46  	}
    47  
    48  	go func() {
    49  		log.Println("Starting server on port:", port)
    50  		log.Fatal(httpServer.ListenAndServe())
    51  	}()
    52  
    53  	shutdown := make(chan os.Signal, 0)
    54  	signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
    55  
    56  	<-shutdown
    57  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    58  	log.Println("Shutting down server gracefully in 1 second.")
    59  	time.Sleep(time.Second)
    60  	defer cancel()
    61  
    62  	log.Fatal(httpServer.Shutdown(ctx))
    63  	os.Exit(0)
    64  }