Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 6.54 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.  
  6.     "github.com/gin-gonic/gin"
  7.     "github.com/jinzhu/gorm"
  8.     _ "github.com/lib/pq" //this is a driver
  9. )
  10.  
  11. var db *gorm.DB
  12. var err error
  13.  
  14. //NOTE TO SELF: This is a One-to-Many relationships, User can have many cars, a car can't be owned by two people
  15.  
  16. //fields in struct need to start with a capital letter, this is how Go understands these are public
  17. type User struct {
  18.     //gorm.Model //-> better alternative than uint for PK, adds created at, deleted at... and other stuff
  19.     ID        uint   `gorm:"primary_key"` //selected as PKEY by default
  20.     FirstName string `gorm:"column:FirstName"`
  21.     LastName  string `gorm:"column:LastName"`
  22.     Cars      []Car  `gorm:"ForeignKey:UserID"` //one to many
  23.     //old m2m: `gorm:"many2many:dmv;"` //creates user_cars as intermediary table and sets pk*
  24. }
  25.  
  26. type Car struct { //define table Car
  27.     //gorm.Model
  28.     ID      uint   `gorm:"primary_key"`
  29.     UserID  uint   //sets UserID PK from User table as FK in Car table
  30.     CarName string `gorm:"column:CarName"`
  31.     CarReg  string `gorm:"column:CarReg"`
  32. }
  33.  
  34. func main() {
  35.     // NOTE TO SELF! use = to assign the global var, spent 2hrs debugging this because the log is terrible
  36.     // := assign it only in this function (locally)
  37.     //standard stuff to access postgredb
  38.     db, err = gorm.Open("postgres", "user=postgres password=vegeta dbname=gorm sslmode=disable")
  39.     if err != nil {
  40.         panic(err.Error())
  41.     }
  42.     defer db.Close()
  43.  
  44.     //Prototyping stuff only
  45.     /*
  46.         //This will create a DB if there is none
  47.         db.CreateTable(&User{})
  48.         db.CreateTable(&Car{})
  49.  
  50.         //inserting data into tables - many to many - directly!!
  51.         user := User{
  52.             FirstName: "Haso",
  53.             LastName:  "Veliki",
  54.             Cars: []Car{
  55.                 {CarName: "Golf", CarReg: "G-73"},
  56.                 {CarName: "Mercedes", CarReg: "M-007"},
  57.             },
  58.         }
  59.  
  60.         db.Create(&user)
  61.         db.Save(&user) //use db.Debug().Save(...) to see what is happening in SQL
  62.  
  63.         //automating some basic inputs for testing...
  64.         userB := User{
  65.             FirstName: "Suljo",
  66.             LastName:  "Mali",
  67.             Cars: []Car{
  68.                 {CarName: "Skoda", CarReg: "S-23"},
  69.             },
  70.         }
  71.         db.Create(&userB)
  72.         db.Save(&userB)
  73.     */
  74.     //Warning for some reason, gorm always autodoes a plural of table... car becomes cars etc.
  75.     //Note to self: You can avoid the renaming above by using something like: `gorm:"column:nameoftable"`
  76.  
  77.     r := gin.Default() //initializing default router
  78.     r.GET("/people/", GetPeople)
  79.     r.GET("/people/:id", GetUser)
  80.     r.GET("/cars", GetCars)
  81.     r.GET("/cars/:id", GetCar)
  82.     r.GET("/dmv/:id", GetUserCars)
  83.     r.GET("/dmv/", GetUsersCars)
  84.     //NOTE TO SELF do not close /.../ if you're going to use POST
  85.     r.POST("/people", CreateUser)
  86.     r.PUT("/people/:id", UpdateUser)
  87.     r.PUT("/cars/:id", UpdateCar)
  88.     r.DELETE("/people/:id", DeleteUser)
  89.     r.DELETE("/car/:id", DeleteCar)
  90.  
  91.     r.Run(":8080") //r.Run() would've defaulted to 8080 anyways
  92. }
  93.  
  94. //DELETE
  95. //delete user with his/her cars
  96. func DeleteUser(c *gin.Context) {
  97.     id := c.Params.ByName("id")
  98.     var user User
  99.     var car Car
  100.     d2 := db.Debug().Where("cars.user_id = ?", id).Delete(&car)
  101.     d := db.Debug().Where("id = ?", id).Delete(&user)
  102.     fmt.Println(d)
  103.     fmt.Println(d2)
  104.     c.JSON(200, gin.H{"id #" + id: "deleted"})
  105. }
  106.  
  107. //delete car
  108. func DeleteCar(c *gin.Context) {
  109.     id := c.Params.ByName("id")
  110.     var car Car
  111.     d := db.Where("id = ?", id).Delete(&car)
  112.     fmt.Println(d)
  113.     c.JSON(200, gin.H{"id #" + id: "deleted"})
  114. }
  115.  
  116. //UPDATE
  117. //update user
  118. func UpdateUser(c *gin.Context) {
  119.     var user User
  120.     id := c.Params.ByName("id")
  121.     if err := db.Where("id = ?", id).First(&user).Error; err != nil {
  122.         c.AbortWithStatus(404)
  123.         fmt.Println(err)
  124.     }
  125.     c.BindJSON(&user)
  126.  
  127.     db.Save(&user)
  128.     c.JSON(200, user)
  129. }
  130.  
  131. //update car
  132. func UpdateCar(c *gin.Context) {
  133.     var car Car
  134.     id := c.Params.ByName("id")
  135.     if err := db.Where("id = ?", id).First(&car).Error; err != nil {
  136.         c.AbortWithStatus(404)
  137.         fmt.Println(err)
  138.     }
  139.     c.BindJSON(&car)
  140.     db.Save(&car)
  141.     c.JSON(200, car)
  142. }
  143.  
  144. //CREATE
  145. //NOTE TO SELF, use the following format to post:
  146. // {"FirstName":"Velid","LastName":"Sadovic","Cars":[{"CarName":"Suzuki","CarReg":"Jeep-23"},{second car...}]}
  147. func CreateUser(c *gin.Context) {
  148.     var user User
  149.     c.BindJSON(&user)
  150.  
  151.     db.Create(&user)
  152.     c.JSON(200, user)
  153. }
  154.  
  155. //GET
  156. //get specific user
  157. func GetUser(c *gin.Context) {
  158.     id := c.Params.ByName("id")
  159.     var user User
  160.     if err := db.Where("id = ?", id).First(&user).Error; err != nil {
  161.         c.AbortWithStatus(404)
  162.         fmt.Println(err)
  163.     } else {
  164.         c.JSON(200, user)
  165.     }
  166. }
  167.  
  168. //get specific car
  169. func GetCar(c *gin.Context) {
  170.     id := c.Params.ByName("id")
  171.     var car Car
  172.     if err := db.Where("id = ?", id).First(&car).Error; err != nil {
  173.         c.AbortWithStatus(404)
  174.         fmt.Println(err)
  175.     } else {
  176.         c.JSON(200, car)
  177.     }
  178. }
  179.  
  180. //get specific user and their cars
  181. func GetUserCars(c *gin.Context) {
  182.     id := c.Params.ByName("id")
  183.     var user User
  184.     if err := db.Debug().Joins("JOIN cars ON users.id = cars.user_id").
  185.         Where("users.id = ?", id).Preload("Cars").Find(&user).Error; err != nil {
  186.         c.AbortWithStatus(404)
  187.         fmt.Println(err)
  188.     } else {
  189.         c.JSON(200, user)
  190.     }
  191. }
  192.  
  193. //get all and their cars
  194. func GetUsersCars(c *gin.Context) {
  195.     var users []User
  196.     //NOTE TO SELF - > PRELOAD IS VERY IMPORTANT! RELATED STRUCTS NOT LOADED BY DEFAULT!
  197.     if err := db.Debug().Joins("JOIN cars ON users.id = cars.user_id").
  198.         Preload("Cars").Find(&users).Error; err != nil {
  199.         c.AbortWithStatus(404)
  200.         fmt.Println(err)
  201.     } else {
  202.         c.JSON(200, users)
  203.     }
  204. }
  205.  
  206. //GET ALL
  207. //get all users
  208. func GetPeople(c *gin.Context) {
  209.     var users []User
  210.     if err := db.Find(&users).Error; err != nil {
  211.         c.AbortWithStatus(404)
  212.         fmt.Println(err)
  213.     } else {
  214.         c.JSON(200, users)
  215.     }
  216. }
  217.  
  218. //get all cars
  219. func GetCars(c *gin.Context) {
  220.     var cars []Car
  221.     if err := db.Find(&cars).Error; err != nil {
  222.         c.AbortWithStatus(404)
  223.         fmt.Println(err)
  224.     } else {
  225.         c.JSON(200, cars)
  226.     }
  227. }
  228.  
  229. //old code, not clean
  230. /*
  231. func GetPeople(c *gin.Context) {
  232.     if err != nil {
  233.         c.AbortWithStatus(404)
  234.     } else {
  235.         var people []User
  236.         c.JSON(200, db.Find(&people))
  237.     }
  238. }
  239. */
  240.  
  241. //old stuff
  242. /*
  243.     r.GET("/ping", func(c *gin.Context) {
  244.         c.JSON(200, gin.H{
  245.             "message": "pong",
  246.         })
  247.     })
  248. */
  249.  
  250. //building an API not web app, switching to JSON
  251. /*
  252. func main() {
  253.     r := gin.Default()
  254.     r.GET("/", func(c *gin.Context) {
  255.         c.JSON(200, gin.H{
  256.             "message": "Hello World",
  257.         })
  258.     })
  259.     r.Run() // listen and server on 0.0.0.0:8080
  260. }
  261.  
  262.     //db.Delete(Car{}, "name LIKE ?", "%Mercedes%")
  263.     //// DELETE from cars table, where car name is Mercedes
  264.  
  265.     //db.AutoMigrate(&User{}) //used for changing the model - schema on the fly
  266. //for _, cr := range cars {
  267.     //}
  268. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement