adding gorm

This commit is contained in:
2025-11-17 22:26:21 +00:00
parent ff32c4fa8e
commit fee7e26336
4 changed files with 64 additions and 1 deletions

View File

@@ -1,3 +1,12 @@
module adam-french.co.uk/simplebackend module adam-french.co.uk/backend
go 1.22 go 1.22
require (
github.com/gin-gonic/gin v1.9.1
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.10.7
github.com/sirupsen/logrus v1.9.3
gorm.io/gorm v1.26.0
gorm.io/driver/postgres v1.5.0
)

View File

@@ -3,9 +3,42 @@ package main
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"adam-french.co.uk/backend/models"
) )
func connectToPostgreSQL() (*gorm.DB, error) {
dsn := "user=postgres password=password dbname=simplebackend host=localhost port=5432 sslmode=disable"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}
func main() { func main() {
db, err := connectToPostgreSQL()
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Perform database migration
err = db.AutoMigrate(&models.User{})
if err != nil {
log.Fatal(err)
}
err = db.AutoMigrate(&models.Post{})
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello from Go!") fmt.Fprintln(w, "Hello from Go!")
}) })

11
backend/models/post.go Normal file
View File

@@ -0,0 +1,11 @@
package models
import "gorm.io/gorm"
type Post struct {
gorm.Model // includes ID, CreatedAt, UpdatedAt, DeletedAt
Title string `gorm:"not null"`
Content string `gorm:"type:text; not null"`
AuthorID uint // foreign key to User
Author User `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"` // optional relation
}

10
backend/models/user.go Normal file
View File

@@ -0,0 +1,10 @@
package models
import "gorm.io/gorm"
type User struct {
gorm.Model // includes ID, CreatedAt, UpdatedAt, DeletedAt
Name string
Email string `gorm:"uniqueIndex"`
Password string
}