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

57
main.go
View File

@@ -2,51 +2,38 @@ package main
import (
"fmt"
"path"
"path/filepath"
"os"
"git.cosysda.de/HuskyTeufel/Hochzeit/handlers"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/joho/godotenv"
"github.com/labstack/gommon/log"
)
func main() {
fmt.Println("Hallo")
r := gin.Default()
r.Use(CORSMiddleware())
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))
}
}))
r.GET("/besucher", handlers.GetBesucherListHandler)
r.POST("/besucher", handlers.AddBesucherHandler)
r.DELETE("/besucher/:id", handlers.DeleteBesucherHandler)
r.PUT("/besucher", handlers.ComeBesucherHandler)
err := r.Run(":3001")
err := godotenv.Load(".env")
if err != nil {
panic(err)
log.Fatalf("ENV file not found")
}
}
dbhost := os.Getenv("DB_HOST")
dbuser := os.Getenv("DB_USER")
dbpass := os.Getenv("DB_PASS")
dbdata := os.Getenv("DB_DATA")
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")
connectionstring := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", dbhost, dbuser, dbpass, dbdata)
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
db, err := gorm.Open("postgres", connectionstring)
if err != nil {
panic(err.Error())
}
app := App{
db: db,
r: gin.Default(),
}
app.start()
//r := gin.Default()
}
/*func terminateWithError(statusCode int, message string, c *gin.Context) {