Skip to content

Commit

Permalink
Add new config fields.
Browse files Browse the repository at this point in the history
  • Loading branch information
efectn committed Feb 25, 2022
1 parent 33c2694 commit 0908eba
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 92 deletions.
4 changes: 2 additions & 2 deletions cmd/example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func main() {
}

// Setup webserver
ws, err := webserver.SetupWebServer(config)
ws, err := webserver.SetupApp(config)
if err != nil && !fiber.IsChild() {
log.Panic().Err(err).Msg("")
}
Expand All @@ -26,7 +26,7 @@ func main() {
ws.SetupLogger()

// Register Routes
routes.RegisterAPIRoutes(ws.App)
routes.RegisterAPIRoutes(ws.Fiber)

// Run webserver
go func() {
Expand Down
45 changes: 26 additions & 19 deletions config/example.toml
Original file line number Diff line number Diff line change
@@ -1,36 +1,43 @@
[webserver]
header = "Fiber"
app_name = "Fiber"
# Configuration vars for cmd/app
[app]
name = "Fiber Boilerplate"
port = ":8080"
idle-timeout = 5 # As seconds
print-routes = false
prefork = true
production = false

[app.tls]
enable = false
cert-file = "./storage/selfsigned.crt"
key-file = "./storage/selfsigned.key"

[logger]
time-format = "" # https://pkg.go.dev/time#pkg-constants, https://github.com/rs/zerolog/blob/master/api.go#L10
level = 0 # panic -> 5, fatal -> 4, error -> 3, warn -> 2, info -> 1, debug -> 0, trace -> -1
prettier = true

[limiter]
enabled = false
max = 20
expiration_seconds = 60
[middleware.compress]
enable = true
level = 1

[session]
enabled = true
expiration_hours = 24
[middleware.recover]
enable = true

[compress]
enabled = true
level = 2
[middleware.monitor]
enable = false
path = "/monitor"

[recover]
enabled = true
[middleware.pprof]
enable = true

[monitor]
enabled = true
[middleware.limiter]
enable = false
max = 20
expiration_seconds = 60

[filesystem]
enabled = true
[middleware.filesystem]
enable = false
browse = true
max_age = 3600
index = "index.html"
Expand Down
80 changes: 50 additions & 30 deletions pkg/utils/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,73 @@ package config
import (
"os"
"strings"
"time"

"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/pelletier/go-toml/v2"
"github.com/rs/zerolog"
)

type Config struct {
Webserver struct {
Header string
AppName string `toml:"app_name"`
Port string
Prefork bool
Production bool
}
Logger struct {
TimeFormat string `toml:"time-format"`
Level zerolog.Level `toml:"level"`
Prettier bool `toml:"prettier"`
}
Limiter struct {
Enabled bool
Max int
ExpSecs int `toml:"expiration_seconds"`
}
Session struct {
Enabled bool
ExpHrs int `toml:"expiration_hours"`
type app = struct {
Name string `toml:"name"`
Port string `toml:"port"`
PrintRoutes bool `toml:"print-routes"`
Prefork bool `toml:"prefork"`
Production bool `toml:"production"`
IdleTimeout time.Duration `toml:"idle-timeout"`
TLS struct {
Enable bool
CertFile string `toml:"cert-file"`
KeyFile string `toml:"key-file"`
}
}

type logger = struct {
TimeFormat string `toml:"time-format"`
Level zerolog.Level `toml:"level"`
Prettier bool `toml:"prettier"`
}

type middleware = struct {
Compress struct {
Enabled bool
Level compress.Level
Enable bool
Level compress.Level
}

Recover struct {
Enabled bool
Enable bool
}

Monitor struct {
Enabled bool
Enable bool
Path string
}

Pprof struct {
Enable bool
}

Limiter struct {
Enable bool
Max int
ExpSecs time.Duration `toml:"expiration_seconds"`
}

Filesystem struct {
Enabled bool
Browse bool
MaxAge int `toml:"max_age"`
Index string
Root string
Enable bool
Browse bool
MaxAge int `toml:"max_age"`
Index string
Root string
}
}

type Config struct {
App app
Logger logger
Middleware middleware
}

func ParseConfig(name string, debug ...bool) (*Config, error) {
var contents *Config
var file []byte
Expand Down
5 changes: 2 additions & 3 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@ type errorResponse struct {
}

func IsEnabled(key bool) func(c *fiber.Ctx) bool {
enabled := true
if key {
enabled = false
return nil
}

return func(c *fiber.Ctx) bool { return enabled }
return func(c *fiber.Ctx) bool { return true }
}

func ValidateStruct(input interface{}) []*errorResponse {
Expand Down
87 changes: 49 additions & 38 deletions pkg/webserver/webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,26 @@ import (
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/gofiber/fiber/v2/middleware/limiter"
"github.com/gofiber/fiber/v2/middleware/monitor"
"github.com/gofiber/fiber/v2/middleware/pprof"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/session"
futils "github.com/gofiber/fiber/v2/utils"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

type WebServer struct {
App *fiber.App
Store *session.Store
Fiber *fiber.App
Config *config.Config
Logger zerolog.Logger
}

func SetupWebServer(config *config.Config) (*WebServer, error) {
func SetupApp(config *config.Config) (*WebServer, error) {
// Setup Webserver
ws := &WebServer{
App: fiber.New(fiber.Config{
ServerHeader: config.Webserver.Header,
AppName: config.Webserver.AppName,
Prefork: config.Webserver.Prefork,
Fiber: fiber.New(fiber.Config{
ServerHeader: config.App.Name,
AppName: config.App.Name,
Prefork: config.App.Prefork,
ErrorHandler: func(c *fiber.Ctx, err error) error {
code := fiber.StatusInternalServerError
var messages interface{}
Expand All @@ -59,43 +58,46 @@ func SetupWebServer(config *config.Config) (*WebServer, error) {
})
},
DisableStartupMessage: true,
}),
Store: session.New(session.Config{
Expiration: time.Duration(config.Session.ExpHrs) * time.Hour,
IdleTimeout: config.App.IdleTimeout * time.Second,
EnablePrintRoutes: config.App.PrintRoutes,
}),
Config: config,
Logger: zerolog.Logger{},
}

// Add Extra Middlewares
ws.App.Use(limiter.New(limiter.Config{
Next: utils.IsEnabled(config.Limiter.Enabled),
Max: config.Limiter.Max,
Expiration: time.Duration(config.Session.ExpHrs) * time.Hour,
ws.Fiber.Use(limiter.New(limiter.Config{
Next: utils.IsEnabled(config.Middleware.Limiter.Enable),
Max: config.Middleware.Limiter.Max,
Expiration: config.Middleware.Limiter.ExpSecs * time.Second,
}))

ws.Fiber.Use(compress.New(compress.Config{
Next: utils.IsEnabled(config.Middleware.Compress.Enable),
Level: config.Middleware.Compress.Level,
}))

ws.App.Use(compress.New(compress.Config{
Next: utils.IsEnabled(config.Compress.Enabled),
Level: config.Compress.Level,
ws.Fiber.Use(recover.New(recover.Config{
Next: utils.IsEnabled(config.Middleware.Recover.Enable),
}))

ws.App.Use(recover.New(recover.Config{
Next: utils.IsEnabled(config.Recover.Enabled),
ws.Fiber.Use(pprof.New(pprof.Config{
Next: utils.IsEnabled(config.Middleware.Pprof.Enable),
}))

ws.App.Use(filesystem.New(filesystem.Config{
Next: utils.IsEnabled(config.Filesystem.Enabled),
Root: http.Dir(config.Filesystem.Root),
Browse: config.Filesystem.Browse,
MaxAge: config.Filesystem.MaxAge,
ws.Fiber.Use(filesystem.New(filesystem.Config{
Next: utils.IsEnabled(config.Middleware.Filesystem.Enable),
Root: http.Dir(config.Middleware.Filesystem.Root),
Browse: config.Middleware.Filesystem.Browse,
MaxAge: config.Middleware.Filesystem.MaxAge,
}))

// Test Routes
ws.App.Get("/ping", func(c *fiber.Ctx) error {
ws.Fiber.Get("/ping", func(c *fiber.Ctx) error {
return c.Status(200).SendString("Pong! 👋")
})

ws.App.Get("/html", func(c *fiber.Ctx) error {
ws.Fiber.Get("/html", func(c *fiber.Ctx) error {
example, err := storage.Private.ReadFile("private/example.html")
if err != nil {
panic(err)
Expand All @@ -105,8 +107,8 @@ func SetupWebServer(config *config.Config) (*WebServer, error) {
return c.Status(200).SendString(string(example))
})

ws.App.Get("/monitor", monitor.New(monitor.Config{
Next: utils.IsEnabled(config.Monitor.Enabled),
ws.Fiber.Get(config.Middleware.Monitor.Path, monitor.New(monitor.Config{
Next: utils.IsEnabled(config.Middleware.Monitor.Enable),
}))

return ws, nil
Expand All @@ -128,9 +130,9 @@ func (ws *WebServer) SetupLogger() error {

func (ws *WebServer) ListenWebServer() error {
// Custom Startup Messages
host, port := config.ParseAddr(ws.Config.Webserver.Port)
host, port := config.ParseAddr(ws.Config.App.Port)
if host == "" {
if ws.App.Config().Network == "tcp6" {
if ws.Fiber.Config().Network == "tcp6" {
host = "[::1]"
} else {
host = "0.0.0.0"
Expand All @@ -148,13 +150,13 @@ func (ws *WebServer) ListenWebServer() error {
}

// Information message
ws.Logger.Info().Msg(ws.App.Config().AppName + " is running at the moment!")
ws.Logger.Info().Msg(ws.Fiber.Config().AppName + " is running at the moment!")

// Debug informations
if !ws.Config.Webserver.Production {
if !ws.Config.App.Production {
prefork := "Enabled"
procs := runtime.GOMAXPROCS(0)
if !ws.Config.Webserver.Prefork {
if !ws.Config.App.Prefork {
procs = 1
prefork = "Disabled"
}
Expand All @@ -163,12 +165,21 @@ func (ws *WebServer) ListenWebServer() error {
ws.Logger.Debug().Msgf("Host: %s", host)
ws.Logger.Debug().Msgf("Port: %s", port)
ws.Logger.Debug().Msgf("Prefork: %s", prefork)
ws.Logger.Debug().Msgf("Handlers: %d", ws.App.HandlersCount())
ws.Logger.Debug().Msgf("Handlers: %d", ws.Fiber.HandlersCount())
ws.Logger.Debug().Msgf("Processes: %d", procs)
ws.Logger.Debug().Msgf("PID: %d", os.Getpid())
}

if err = ws.App.Listen(ws.Config.Webserver.Port); err != nil {
// Listen the app (with TLS Support)
if ws.Config.App.TLS.Enable {
ws.Logger.Debug().Msg("TLS support has enabled.")

if err := ws.Fiber.ListenTLS(ws.Config.App.Port, ws.Config.App.TLS.CertFile, ws.Config.App.TLS.KeyFile); err != nil {
return err
}
}

if err := ws.Fiber.Listen(ws.Config.App.Port); err != nil {
return err
}

Expand All @@ -181,12 +192,12 @@ func (ws *WebServer) ShutdownApp() {
<-c

ws.Logger.Info().Msg("Shutting down the app...")
if err := ws.App.Shutdown(); err != nil {
if err := ws.Fiber.Shutdown(); err != nil {
ws.Logger.Panic().Err(err).Msg("")
}

ws.Logger.Info().Msg("Running cleanup tasks...")
ws.Logger.Info().Msgf("%s was successful shutdown.", ws.Config.Webserver.AppName)
ws.Logger.Info().Msgf("%s was successful shutdown.", ws.Config.App.Name)
ws.Logger.Info().Msg("\u001b[96msee you again👋\u001b[0m")

os.Exit(1)
Expand Down

0 comments on commit 0908eba

Please sign in to comment.