Passport/pkg/internal/server/server.go

85 lines
2.2 KiB
Go
Raw Normal View History

2024-01-06 17:56:32 +00:00
package server
import (
"git.solsynth.dev/hydrogen/passport/pkg/internal/server/admin"
"git.solsynth.dev/hydrogen/passport/pkg/internal/server/api"
"git.solsynth.dev/hydrogen/passport/pkg/internal/server/exts"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"net/http"
"path/filepath"
"strings"
2024-01-26 17:11:32 +00:00
"github.com/gofiber/fiber/v2"
2024-01-30 11:20:12 +00:00
"github.com/gofiber/fiber/v2/middleware/cors"
2024-04-20 06:05:50 +00:00
"github.com/gofiber/fiber/v2/middleware/favicon"
2024-01-30 11:20:12 +00:00
"github.com/gofiber/fiber/v2/middleware/idempotency"
"github.com/gofiber/fiber/v2/middleware/logger"
2024-01-26 17:11:32 +00:00
jsoniter "github.com/json-iterator/go"
"github.com/rs/zerolog/log"
2024-01-06 17:56:32 +00:00
"github.com/spf13/viper"
)
type HTTPApp struct {
app *fiber.App
}
2024-04-20 06:05:50 +00:00
func NewServer() *HTTPApp {
app := fiber.New(fiber.Config{
2024-01-26 17:11:32 +00:00
DisableStartupMessage: true,
EnableIPValidation: true,
2024-04-20 06:05:50 +00:00
ServerHeader: "Hydrogen.Passport",
AppName: "Hydrogen.Passport",
ProxyHeader: fiber.HeaderXForwardedFor,
2024-01-26 17:11:32 +00:00
JSONEncoder: jsoniter.ConfigCompatibleWithStandardLibrary.Marshal,
JSONDecoder: jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal,
EnablePrintRoutes: viper.GetBool("debug.print_routes"),
2024-01-26 17:11:32 +00:00
})
2024-01-06 17:56:32 +00:00
app.Use(idempotency.New())
app.Use(cors.New(cors.Config{
2024-01-30 11:20:12 +00:00
AllowCredentials: true,
AllowMethods: strings.Join([]string{
fiber.MethodGet,
fiber.MethodPost,
fiber.MethodHead,
fiber.MethodOptions,
fiber.MethodPut,
fiber.MethodDelete,
fiber.MethodPatch,
}, ","),
AllowOriginsFunc: func(origin string) bool {
return true
},
}))
app.Use(logger.New(logger.Config{
2024-01-30 11:20:12 +00:00
Format: "${status} | ${latency} | ${method} ${path}\n",
Output: log.Logger,
2024-01-30 10:55:55 +00:00
}))
app.Use(exts.AuthMiddleware)
2024-06-30 03:52:36 +00:00
admin.MapAdminAPIs(app)
api.MapAPIs(app)
app.Use(filesystem.New(filesystem.Config{
Root: http.Dir(viper.GetString("frontend_app")),
Index: "index.html",
NotFoundFile: "index.html",
MaxAge: 3600,
}))
2024-04-20 06:05:50 +00:00
app.Use(favicon.New(favicon.Config{
File: filepath.Join(viper.GetString("frontend_app"), "favicon.png"),
URL: "/favicon.png",
2024-01-30 11:20:12 +00:00
}))
2024-04-20 06:05:50 +00:00
return &HTTPApp{app}
2024-01-06 17:56:32 +00:00
}
func (v *HTTPApp) Listen() {
if err := v.app.Listen(viper.GetString("bind")); err != nil {
2024-01-26 17:11:32 +00:00
log.Fatal().Err(err).Msg("An error occurred when starting server...")
2024-01-06 17:56:32 +00:00
}
}