Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/jinzhu/gorm"
- _ "github.com/lib/pq" //this is a driver
- )
- var db *gorm.DB
- var err error
- //NOTE TO SELF: This is a One-to-Many relationships, User can have many cars, a car can't be owned by two people
- //fields in struct need to start with a capital letter, this is how Go understands these are public
- type User struct {
- //gorm.Model //-> better alternative than uint for PK, adds created at, deleted at... and other stuff
- ID uint `gorm:"primary_key"` //selected as PKEY by default
- FirstName string `gorm:"column:FirstName"`
- LastName string `gorm:"column:LastName"`
- Cars []Car `gorm:"ForeignKey:UserID"` //one to many
- //old m2m: `gorm:"many2many:dmv;"` //creates user_cars as intermediary table and sets pk*
- }
- type Car struct { //define table Car
- //gorm.Model
- ID uint `gorm:"primary_key"`
- UserID uint //sets UserID PK from User table as FK in Car table
- CarName string `gorm:"column:CarName"`
- CarReg string `gorm:"column:CarReg"`
- }
- func main() {
- // NOTE TO SELF! use = to assign the global var, spent 2hrs debugging this because the log is terrible
- // := assign it only in this function (locally)
- //standard stuff to access postgredb
- db, err = gorm.Open("postgres", "user=postgres password=vegeta dbname=gorm sslmode=disable")
- if err != nil {
- panic(err.Error())
- }
- defer db.Close()
- //Prototyping stuff only
- /*
- //This will create a DB if there is none
- db.CreateTable(&User{})
- db.CreateTable(&Car{})
- //inserting data into tables - many to many - directly!!
- user := User{
- FirstName: "Haso",
- LastName: "Veliki",
- Cars: []Car{
- {CarName: "Golf", CarReg: "G-73"},
- {CarName: "Mercedes", CarReg: "M-007"},
- },
- }
- db.Create(&user)
- db.Save(&user) //use db.Debug().Save(...) to see what is happening in SQL
- //automating some basic inputs for testing...
- userB := User{
- FirstName: "Suljo",
- LastName: "Mali",
- Cars: []Car{
- {CarName: "Skoda", CarReg: "S-23"},
- },
- }
- db.Create(&userB)
- db.Save(&userB)
- */
- //Warning for some reason, gorm always autodoes a plural of table... car becomes cars etc.
- //Note to self: You can avoid the renaming above by using something like: `gorm:"column:nameoftable"`
- r := gin.Default() //initializing default router
- r.GET("/people/", GetPeople)
- r.GET("/people/:id", GetUser)
- r.GET("/cars", GetCars)
- r.GET("/cars/:id", GetCar)
- r.GET("/dmv/:id", GetUserCars)
- r.GET("/dmv/", GetUsersCars)
- //NOTE TO SELF do not close /.../ if you're going to use POST
- r.POST("/people", CreateUser)
- r.PUT("/people/:id", UpdateUser)
- r.PUT("/cars/:id", UpdateCar)
- r.DELETE("/people/:id", DeleteUser)
- r.DELETE("/car/:id", DeleteCar)
- r.Run(":8080") //r.Run() would've defaulted to 8080 anyways
- }
- //DELETE
- //delete user with his/her cars
- func DeleteUser(c *gin.Context) {
- id := c.Params.ByName("id")
- var user User
- var car Car
- d2 := db.Debug().Where("cars.user_id = ?", id).Delete(&car)
- d := db.Debug().Where("id = ?", id).Delete(&user)
- fmt.Println(d)
- fmt.Println(d2)
- c.JSON(200, gin.H{"id #" + id: "deleted"})
- }
- //delete car
- func DeleteCar(c *gin.Context) {
- id := c.Params.ByName("id")
- var car Car
- d := db.Where("id = ?", id).Delete(&car)
- fmt.Println(d)
- c.JSON(200, gin.H{"id #" + id: "deleted"})
- }
- //UPDATE
- //update user
- func UpdateUser(c *gin.Context) {
- var user User
- id := c.Params.ByName("id")
- if err := db.Where("id = ?", id).First(&user).Error; err != nil {
- c.AbortWithStatus(404)
- fmt.Println(err)
- }
- c.BindJSON(&user)
- db.Save(&user)
- c.JSON(200, user)
- }
- //update car
- func UpdateCar(c *gin.Context) {
- var car Car
- id := c.Params.ByName("id")
- if err := db.Where("id = ?", id).First(&car).Error; err != nil {
- c.AbortWithStatus(404)
- fmt.Println(err)
- }
- c.BindJSON(&car)
- db.Save(&car)
- c.JSON(200, car)
- }
- //CREATE
- //NOTE TO SELF, use the following format to post:
- // {"FirstName":"Velid","LastName":"Sadovic","Cars":[{"CarName":"Suzuki","CarReg":"Jeep-23"},{second car...}]}
- func CreateUser(c *gin.Context) {
- var user User
- c.BindJSON(&user)
- db.Create(&user)
- c.JSON(200, user)
- }
- //GET
- //get specific user
- func GetUser(c *gin.Context) {
- id := c.Params.ByName("id")
- var user User
- if err := db.Where("id = ?", id).First(&user).Error; err != nil {
- c.AbortWithStatus(404)
- fmt.Println(err)
- } else {
- c.JSON(200, user)
- }
- }
- //get specific car
- func GetCar(c *gin.Context) {
- id := c.Params.ByName("id")
- var car Car
- if err := db.Where("id = ?", id).First(&car).Error; err != nil {
- c.AbortWithStatus(404)
- fmt.Println(err)
- } else {
- c.JSON(200, car)
- }
- }
- //get specific user and their cars
- func GetUserCars(c *gin.Context) {
- id := c.Params.ByName("id")
- var user User
- if err := db.Debug().Joins("JOIN cars ON users.id = cars.user_id").
- Where("users.id = ?", id).Preload("Cars").Find(&user).Error; err != nil {
- c.AbortWithStatus(404)
- fmt.Println(err)
- } else {
- c.JSON(200, user)
- }
- }
- //get all and their cars
- func GetUsersCars(c *gin.Context) {
- var users []User
- //NOTE TO SELF - > PRELOAD IS VERY IMPORTANT! RELATED STRUCTS NOT LOADED BY DEFAULT!
- if err := db.Debug().Joins("JOIN cars ON users.id = cars.user_id").
- Preload("Cars").Find(&users).Error; err != nil {
- c.AbortWithStatus(404)
- fmt.Println(err)
- } else {
- c.JSON(200, users)
- }
- }
- //GET ALL
- //get all users
- func GetPeople(c *gin.Context) {
- var users []User
- if err := db.Find(&users).Error; err != nil {
- c.AbortWithStatus(404)
- fmt.Println(err)
- } else {
- c.JSON(200, users)
- }
- }
- //get all cars
- func GetCars(c *gin.Context) {
- var cars []Car
- if err := db.Find(&cars).Error; err != nil {
- c.AbortWithStatus(404)
- fmt.Println(err)
- } else {
- c.JSON(200, cars)
- }
- }
- //old code, not clean
- /*
- func GetPeople(c *gin.Context) {
- if err != nil {
- c.AbortWithStatus(404)
- } else {
- var people []User
- c.JSON(200, db.Find(&people))
- }
- }
- */
- //old stuff
- /*
- r.GET("/ping", func(c *gin.Context) {
- c.JSON(200, gin.H{
- "message": "pong",
- })
- })
- */
- //building an API not web app, switching to JSON
- /*
- func main() {
- r := gin.Default()
- r.GET("/", func(c *gin.Context) {
- c.JSON(200, gin.H{
- "message": "Hello World",
- })
- })
- r.Run() // listen and server on 0.0.0.0:8080
- }
- //db.Delete(Car{}, "name LIKE ?", "%Mercedes%")
- //// DELETE from cars table, where car name is Mercedes
- //db.AutoMigrate(&User{}) //used for changing the model - schema on the fly
- //for _, cr := range cars {
- //}
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement