goipam/web/router.go

71 lines
1.4 KiB
Go

package web
import (
"fmt"
"log"
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
"git.jmbit.de/jmb/goipam/db"
"git.jmbit.de/jmb/goipam/web/static"
"git.jmbit.de/jmb/goipam/web/ui"
)
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(urlLog())
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))
}
router = ui.GroupWeb(router)
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,
)
}
}