nurrohim11

rest_api.go

Feb 10th, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 3.40 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "bytes"
  5.     "database/sql"
  6.     "fmt"
  7.     "github.com/gin-gonic/gin"
  8.     _ "github.com/go-sql-driver/mysql"
  9.     "log"
  10.     "net/http"
  11. )
  12.  
  13. func main() {
  14.     db, err := sql.Open("mysql", "root:password@/rest_api_go")
  15.     if err != nil {
  16.         log.Fatalln(err)
  17.     }
  18.     defer db.Close()
  19.     // make sure connection is available
  20.     err = db.Ping()
  21.     if err != nil {
  22.         fmt.Print(err.Error())
  23.     }
  24.     type Person struct {
  25.         Id         int
  26.         First_Name string
  27.         Last_Name  string
  28.     }
  29.     router := gin.Default()
  30.  
  31.     // GET a person detail
  32.     router.GET("/person/:id", func(c *gin.Context) {
  33.         var (
  34.             person Person
  35.             result gin.H
  36.         )
  37.         id := c.Param("id")
  38.         row := db.QueryRow("select id, first_name, last_name from person where id = ?;", id)
  39.         err = row.Scan(&person.Id, &person.First_Name, &person.Last_Name)
  40.         if err != nil {
  41.             // If no results send null
  42.             result = gin.H{
  43.                 "result": nil,
  44.                 "count":  0,
  45.             }
  46.         } else {
  47.             result = gin.H{
  48.                 "result": person,
  49.                 "count":  1,
  50.             }
  51.         }
  52.         c.JSON(http.StatusOK, result)
  53.     })
  54.  
  55.     // GET all persons
  56.     router.GET("/persons", func(c *gin.Context) {
  57.         var (
  58.             person  Person
  59.             persons []Person
  60.         )
  61.         rows, err := db.Query("select id, first_name, last_name from person;")
  62.         if err != nil {
  63.             fmt.Print(err.Error())
  64.         }
  65.         for rows.Next() {
  66.             err = rows.Scan(&person.Id, &person.First_Name, &person.Last_Name)
  67.             persons = append(persons, person)
  68.             if err != nil {
  69.                 fmt.Print(err.Error())
  70.             }
  71.         }
  72.         defer rows.Close()
  73.         c.JSON(http.StatusOK, gin.H{
  74.             "result": persons,
  75.             "count":  len(persons),
  76.         })
  77.     })
  78.  
  79.     // POST new person details
  80.     router.POST("/person", func(c *gin.Context) {
  81.         var buffer bytes.Buffer
  82.         first_name := c.PostForm("first_name")
  83.         last_name := c.PostForm("last_name")
  84.         stmt, err := db.Prepare("insert into person (first_name, last_name) values(?,?);")
  85.         if err != nil {
  86.             fmt.Print(err.Error())
  87.         }
  88.         _, err = stmt.Exec(first_name, last_name)
  89.  
  90.         if err != nil {
  91.             fmt.Print(err.Error())
  92.         }
  93.  
  94.         // Fastest way to append strings
  95.         buffer.WriteString(first_name)
  96.         buffer.WriteString(" ")
  97.         buffer.WriteString(last_name)
  98.         defer stmt.Close()
  99.         name := buffer.String()
  100.         c.JSON(http.StatusOK, gin.H{
  101.             "message": fmt.Sprintf(" %s successfully created", name),
  102.         })
  103.     })
  104.  
  105.     // PUT - update a person details
  106.     router.PUT("/person", func(c *gin.Context) {
  107.         var buffer bytes.Buffer
  108.         id := c.Query("id")
  109.         first_name := c.PostForm("first_name")
  110.         last_name := c.PostForm("last_name")
  111.         stmt, err := db.Prepare("update person set first_name= ?, last_name= ? where id= ?;")
  112.         if err != nil {
  113.             fmt.Print(err.Error())
  114.         }
  115.         _, err = stmt.Exec(first_name, last_name, id)
  116.         if err != nil {
  117.             fmt.Print(err.Error())
  118.         }
  119.  
  120.         // Fastest way to append strings
  121.         buffer.WriteString(first_name)
  122.         buffer.WriteString(" ")
  123.         buffer.WriteString(last_name)
  124.         defer stmt.Close()
  125.         name := buffer.String()
  126.         c.JSON(http.StatusOK, gin.H{
  127.             "message": fmt.Sprintf("Successfully updated to %s", name),
  128.         })
  129.     })
  130.  
  131.     // Delete resources
  132.     router.DELETE("/person", func(c *gin.Context) {
  133.         id := c.Query("id")
  134.         stmt, err := db.Prepare("delete from person where id= ?;")
  135.         if err != nil {
  136.             fmt.Print(err.Error())
  137.         }
  138.         _, err = stmt.Exec(id)
  139.         if err != nil {
  140.             fmt.Print(err.Error())
  141.         }
  142.         c.JSON(http.StatusOK, gin.H{
  143.             "message": fmt.Sprintf("Successfully deleted user: %s", id),
  144.         })
  145.     })
  146.     router.Run(":3000")
  147. }
Add Comment
Please, Sign In to add comment