2024-02-22 10:18:59 +01:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/spf13/viper"
|
2024-02-22 20:52:37 +01:00
|
|
|
|
|
|
|
"git.jmbit.de/jmb/goipam/db"
|
|
|
|
"git.jmbit.de/jmb/goipam/web/static"
|
|
|
|
"git.jmbit.de/jmb/goipam/web/ui"
|
2024-02-22 10:18:59 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
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())
|
2024-02-22 20:52:37 +01:00
|
|
|
router.Use(urlLog())
|
2024-02-22 10:18:59 +01:00
|
|
|
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))
|
|
|
|
}
|
2024-02-22 20:52:37 +01:00
|
|
|
router = ui.GroupWeb(router)
|
2024-02-22 10:18:59 +01:00
|
|
|
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,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|