kreangkrai

dvdrental_1

Mar 18th, 2019
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.78 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "github.com/gin-gonic/gin"
  6.     "github.com/jackc/pgx"
  7.     "log"
  8.     "net/http"
  9.     "strconv"
  10.     "time"
  11. )
  12.  
  13. type Customers []Customer
  14. type Customer struct {
  15.     CustomerID int       `json:"customer_id"`
  16.     StoreID    int       `json:"store_id"`
  17.     FirstName  string    `json:"first_name"`
  18.     LastName   string    `json:"last_name"`
  19.     Email      string    `json:"email"`
  20.     AddressID  int       `json:"address_id"`
  21.     Activebool bool      `json:"activebool"`
  22.     CreateDate time.Time `json:"create_date"`
  23.     LastUpdate time.Time `json:"last_update"`
  24.     Active     int       `json:"active"`
  25. }
  26.  
  27. func main() {
  28.     r := gin.Default()
  29.     r.GET("/customers", func(c *gin.Context) {
  30.         if limitStr, isExist := c.GetQuery("limit"); isExist {
  31.             limit, _ := strconv.Atoi(limitStr)
  32.             customers := getCustomers(limit)
  33.             c.JSON(http.StatusOK, gin.H{
  34.                 "data": customers,
  35.             })
  36.         }
  37.     })
  38.     r.GET("/customer/:id", func(c *gin.Context) {
  39.         customerID:=c.Param("id")
  40.     })
  41.     r.Run(":8880")
  42. }
  43.  
  44. func getCustomers(limit int) (customers Customers) {
  45.     config := pgx.ConnConfig{Host: "172.17.0.2", Port: 5432, Database: "dvdrental", User: "postgres", Password: "toor123"}
  46.     conn, err := pgx.Connect(config)
  47.     defer conn.Close()
  48.     if err != nil {
  49.         log.Fatalf("Unable to establish connection: %v", err)
  50.     }
  51.  
  52.     // Query customer
  53.     rows, _ := conn.Query("select * from customer limit $1", 10)
  54.     for rows.Next() {
  55.         customer := Customer{}
  56.  
  57.         rows.Scan(&customer.CustomerID, &customer.StoreID, &customer.FirstName, &customer.LastName, &customer.Email, &customer.AddressID, &customer.Activebool, &customer.CreateDate, &customer.LastUpdate, &customer.Active)
  58.  
  59.         customers = append(customers, customer)
  60.     }
  61.  
  62.     // output
  63.     for _, val := range customers {
  64.         fmt.Println(val.FirstName)
  65.     }
  66.     return customers
  67. }
Advertisement
Add Comment
Please, Sign In to add comment