93 lines
1.7 KiB
Go
93 lines
1.7 KiB
Go
package server
|
|
|
|
import (
|
|
"database/sql"
|
|
"html/template"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gin-contrib/cors"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type HttpServer struct {
|
|
config *viper.Viper
|
|
router *gin.Engine
|
|
dbHandler *sql.DB
|
|
}
|
|
|
|
func InitHttpServer(config *viper.Viper, dbHandler *sql.DB) HttpServer {
|
|
|
|
// repository initialisation:
|
|
|
|
// service initialisation:
|
|
|
|
// controller initialisation:
|
|
|
|
// Service API
|
|
router := gin.Default()
|
|
router.Use(cors.Default())
|
|
|
|
// static content
|
|
router.Static("/static", "../static")
|
|
router.GET("/", home)
|
|
|
|
router.GET("/test", Test)
|
|
|
|
// server
|
|
return HttpServer{
|
|
config: config,
|
|
router: router,
|
|
dbHandler: dbHandler,
|
|
}
|
|
}
|
|
|
|
func (hs HttpServer) Start() {
|
|
err := hs.router.Run(hs.config.GetString("http.server_address"))
|
|
if err != nil {
|
|
log.Fatalf("Error while starting HTTP server: %v", err)
|
|
}
|
|
}
|
|
|
|
func Test(ctx *gin.Context) {
|
|
ctx.JSON(http.StatusOK, gin.H{
|
|
"message": "Test",
|
|
})
|
|
}
|
|
|
|
func home(ctx *gin.Context) {
|
|
|
|
/* load templates */
|
|
|
|
tmpl, err := template.ParseFiles(
|
|
"../templates/pages/index.html",
|
|
"../templates/layouts/navbar.html",
|
|
"../templates/layouts/properties.html",
|
|
"../templates/layouts/footer.html")
|
|
|
|
if err != nil {
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
renderTemplate(ctx, tmpl, nil)
|
|
}
|
|
|
|
func renderTemplate(ctx *gin.Context, tmpl *template.Template, data interface{}) {
|
|
if tmpl == nil {
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{
|
|
"error": "template is nil",
|
|
})
|
|
return
|
|
}
|
|
err := tmpl.Execute(ctx.Writer, data)
|
|
if err != nil {
|
|
ctx.JSON(http.StatusInternalServerError, gin.H{
|
|
"error": err.Error(),
|
|
})
|
|
}
|
|
}
|