goipam/web/router.go

67 lines
1.4 KiB
Go
Raw Normal View History

2024-02-22 10:18:59 +01:00
package web
import (
"fmt"
"log"
"net/http"
"git.jmbit.de/jmb/goipam/db"
"git.jmbit.de/jmb/goipam/web/static"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
func Run() error {
router := setupRouter()
address := fmt.Sprintf("%s:%d", viper.GetString("web.host"), viper.GetInt("web.port"))
log.Println("Listening on address", address)
err := router.Run(address)
log.Println("Router is ready")
if err != nil {
log.Panic("Could not start Webserver: ", err)
return err
}
return nil
}
func setupRouter() *gin.Engine {
log.Println("Setting up router")
gin.ForceConsoleColor()
if viper.GetBool("web.prod") == false {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
router.Use(gin.Recovery())
router.Use(sessions.Sessions("session", db.CreateStore()))
err := router.SetTrustedProxies(viper.GetStringSlice("web.trustedProxies"))
router.HTMLRender = &TemplRender{}
if err != nil {
log.Printf("Could not set trusted Proxies: %v", err)
}
if !viper.GetBool("web.prod") {
router.Static("/static", "./web/static")
} else {
router.StaticFS("/static", http.FS(static.StaticFS))
}
return router
}
func urlLog() gin.HandlerFunc {
return func(c *gin.Context) {
log.Printf(
"[INFO] %s: %s: %s",
c.Request.RemoteAddr,
c.Request.Method,
c.Request.URL,
)
}
}