jokes-bapak2/api/main.go

101 lines
2.4 KiB
Go
Raw Normal View History

2021-05-02 07:49:13 +00:00
package main
import (
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
"time"
2021-05-02 07:49:13 +00:00
2021-07-09 12:13:19 +00:00
v1 "github.com/aldy505/jokes-bapak2-api/api/app/v1"
2021-07-09 06:11:11 +00:00
"github.com/aldy505/jokes-bapak2-api/api/app/v1/platform/database"
"github.com/getsentry/sentry-go"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/etag"
"github.com/gofiber/fiber/v2/middleware/limiter"
2021-07-09 12:13:19 +00:00
_ "github.com/joho/godotenv/autoload"
2021-05-02 07:49:13 +00:00
)
func main() {
2021-07-09 06:11:11 +00:00
timeoutDefault, _ := time.ParseDuration("1m")
err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_DSN"),
// Enable printing of SDK debug messages.
// Useful when getting started or trying to figure something out.
Debug: true,
})
if err != nil {
log.Fatal(err)
}
defer sentry.Flush(2 * time.Second)
err = database.Setup()
if err != nil {
sentry.CaptureException(err)
log.Fatal(err)
2021-05-02 07:49:13 +00:00
}
2021-07-09 06:11:11 +00:00
app := fiber.New(fiber.Config{
ReadTimeout: timeoutDefault,
WriteTimeout: timeoutDefault,
ErrorHandler: errorHandler,
})
app.Use(cors.New())
app.Use(limiter.New())
app.Use(etag.New())
2021-07-09 12:13:19 +00:00
app.Mount("/v1", v1.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" {
StartServer(app)
} else {
StartServerWithGracefulShutdown(app)
}
2021-07-09 06:11:11 +00:00
}
func errorHandler(c *fiber.Ctx, err error) error {
sentry.CaptureException(err)
2021-07-09 12:13:19 +00:00
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
2021-07-09 06:11:11 +00:00
"error": "Something went wrong on our end",
})
2021-05-02 07:49:13 +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.
if err := a.Listen(":" + os.Getenv("PORT")); err != nil {
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.
if err := a.Listen(":" + os.Getenv("PORT")); err != nil {
log.Printf("Oops... Server is not running! Reason: %v", err)
}
}