jokes-bapak2/api/main.go

58 lines
1.3 KiB
Go
Raw Normal View History

2021-05-02 07:49:13 +00:00
package main
import (
2021-09-27 10:10:19 +00:00
"jokes-bapak2-api/app"
2021-05-02 07:58:37 +00:00
"log"
2021-07-09 06:11:11 +00:00
"os"
2021-07-09 12:13:19 +00:00
"os/signal"
2021-07-09 06:11:11 +00:00
"github.com/gofiber/fiber/v2"
2021-07-09 12:13:19 +00:00
_ "github.com/joho/godotenv/autoload"
2021-05-02 07:49:13 +00:00
)
func main() {
2021-09-27 10:10:19 +00:00
a := app.New()
2021-07-09 06:11:11 +00:00
2021-07-09 12:13:19 +00:00
// Start server (with or without graceful shutdown).
if os.Getenv("ENV") == "development" {
2021-09-27 10:10:19 +00:00
StartServer(a)
2021-07-09 12:13:19 +00:00
} else {
2021-09-27 10:10:19 +00:00
StartServerWithGracefulShutdown(a)
2021-07-09 12:13:19 +00:00
}
2021-07-09 06:11:11 +00:00
}
2021-07-15 13:00:44 +00:00
2021-07-09 12:13:19 +00:00
// StartServerWithGracefulShutdown function for starting server with a graceful shutdown.
func StartServerWithGracefulShutdown(a *fiber.App) {
// Create channel for idle connections.
idleConnsClosed := make(chan struct{})
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt) // Catch OS signals.
<-sigint
// Received an interrupt signal, shutdown.
if err := a.Shutdown(); err != nil {
// Error from closing listeners, or context timeout:
log.Printf("Oops... Server is not shutting down! Reason: %v", err)
}
close(idleConnsClosed)
}()
// Run server.
2021-08-04 05:56:14 +00:00
if err := a.Listen(os.Getenv("HOST") + ":" + os.Getenv("PORT")); err != nil {
2021-07-09 12:13:19 +00:00
log.Printf("Oops... Server is not running! Reason: %v", err)
}
<-idleConnsClosed
}
// StartServer func for starting a simple server.
func StartServer(a *fiber.App) {
// Run server.
2021-08-04 05:56:14 +00:00
if err := a.Listen(os.Getenv("HOST") + ":" + os.Getenv("PORT")); err != nil {
2021-07-09 12:13:19 +00:00
log.Printf("Oops... Server is not running! Reason: %v", err)
}
}