jokes-bapak2/api/main.go

84 lines
1.9 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-14 18:17:01 +00:00
v1 "jokes-bapak2-api/app/v1"
2021-07-09 06:11:11 +00:00
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/favicon"
2021-07-09 06:11:11 +00:00
"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")
app := fiber.New(fiber.Config{
ReadTimeout: timeoutDefault,
WriteTimeout: timeoutDefault,
})
2021-07-15 13:00:44 +00:00
app.Use(limiter.New(limiter.Config{
2021-07-19 10:22:22 +00:00
Max: 30,
Expiration: 1 * time.Minute,
2021-07-15 13:00:44 +00:00
LimitReached: limitHandler,
}))
app.Use(favicon.New(favicon.Config{
File: "./favicon.png",
}))
2021-07-09 06:11:11 +00:00
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
}
2021-07-15 13:00:44 +00:00
func limitHandler(c *fiber.Ctx) error {
return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{
"message": "we only allow up to 15 request per minute",
})
}
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)
}
}