kreangkrai icon

dvdrental_1

kreangkrai | PRO | 03/19/19 03:28:56 AM UTC | 0 ⭐ | 869 👁️ | Never ⏰ | []
Go |

1.78 KB

|

None

|

0 👍

/

0 👎

package main
 
import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/jackc/pgx"
    "log"
    "net/http"
    "strconv"
    "time"
)
 
type Customers []Customer
type Customer struct {
    CustomerID int       `json:"customer_id"`
    StoreID    int       `json:"store_id"`
    FirstName  string    `json:"first_name"`
    LastName   string    `json:"last_name"`
    Email      string    `json:"email"`
    AddressID  int       `json:"address_id"`
    Activebool bool      `json:"activebool"`
    CreateDate time.Time `json:"create_date"`
    LastUpdate time.Time `json:"last_update"`
    Active     int       `json:"active"`
}
 
func main() {
    r := gin.Default()
    r.GET("/customers", func(c *gin.Context) {
        if limitStr, isExist := c.GetQuery("limit"); isExist {
            limit, _ := strconv.Atoi(limitStr)
            customers := getCustomers(limit)
            c.JSON(http.StatusOK, gin.H{
                "data": customers,
            })
        }
    })
    r.GET("/customer/:id", func(c *gin.Context) {
        customerID:=c.Param("id")
    })
    r.Run(":8880")
}
 
func getCustomers(limit int) (customers Customers) {
    config := pgx.ConnConfig{Host: "172.17.0.2", Port: 5432, Database: "dvdrental", User: "postgres", Password: "toor123"}
    conn, err := pgx.Connect(config)
    defer conn.Close()
    if err != nil {
        log.Fatalf("Unable to establish connection: %v", err)
    }
 
    // Query customer
    rows, _ := conn.Query("select * from customer limit $1", 10)
    for rows.Next() {
        customer := Customer{}
 
        rows.Scan(&customer.CustomerID, &customer.StoreID, &customer.FirstName, &customer.LastName, &customer.Email, &customer.AddressID, &customer.Activebool, &customer.CreateDate, &customer.LastUpdate, &customer.Active)
 
        customers = append(customers, customer)
    }
 
    // output
    for _, val := range customers {
        fmt.Println(val.FirstName)
    }
    return customers
}

Comments