gin und gorm arbeiten gemeinsam

This commit is contained in:
HuskyTeufel
2022-01-17 16:30:00 +01:00
parent 76fa4b5a0b
commit 9a1dca8c97
5 changed files with 135 additions and 60 deletions

55
app.go Normal file
View File

@@ -0,0 +1,55 @@
package main
import (
"path"
"path/filepath"
"git.cosysda.de/HuskyTeufel/Hochzeit/handlers"
"git.cosysda.de/HuskyTeufel/Hochzeit/planner"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
type App struct {
r *gin.Engine
db *gorm.DB
}
func (a *App) start() {
a.db.AutoMigrate(&planner.Besucher{})
a.r.Use(CORSMiddleware())
a.r.NoRoute((func(c *gin.Context) {
dir, file := path.Split(c.Request.RequestURI)
ext := filepath.Ext(file)
if file == "" || ext == "" {
c.File("./ui/dist/ui/index.html")
} else {
c.File("./ui/dist/ui/" + path.Join(dir, file))
}
}))
a.r.GET("/besucher", handlers.GetBesucherListHandler)
a.r.POST("/besucher", handlers.AddBesucherHandler)
a.r.DELETE("/besucher/:id", handlers.DeleteBesucherHandler)
a.r.PUT("/besucher", handlers.ComeBesucherHandler)
err := a.r.Run(":3001")
if err != nil {
panic(err)
}
}
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "DELETE, GET, OPTIONS, POST, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}