package main
import (
"github.com/gin-gonic/gin"
"go101/go001/model"
"log"
"net/http"
"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) {
limit := c.DefaultQuery("limit", "10")
customers := getCustomers(limit)
c.JSON(http.StatusOK, gin.H{
"data": customers,
})
})
r.GET("/customer/:id", func(c *gin.Context) {
customerID := c.Param("id")
customer := getCustomerByID(customerID)
c.JSON(http.StatusOK, gin.H{
"data": customer,
})
})
r.Run(":8880")
}
func getCustomers(limit string) (customers Customers) {
rows, err := model.PgxConn.Query("select * from customer limit $1", limit)
if err != nil {
log.Fatalf("Unable to query: %v", err)
}
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)
}
return customers
}
func getCustomerByID(id string) (customer Customer) {
rows, _ := model.PgxConn.Query("select * from customer as cus where cus.customer_id=$1", id)
for rows.Next() {
rows.Scan(&customer.CustomerID, &customer.StoreID, &customer.FirstName, &customer.LastName, &customer.Email, &customer.AddressID, &customer.Activebool, &customer.CreateDate, &customer.LastUpdate, &customer.Active)
}
return
}
package model
import (
"github.com/jackc/pgx"
"log"
)
var PgxConn *pgx.Conn
func init() {
config := pgx.ConnConfig{Host: "172.17.0.2", Port: 5432, Database: "dvdrental", User: "postgres", Password: "toor123"}
conn, err := pgx.Connect(config)
if err != nil {
log.Fatalf("Unable to establish connection: %v", err)
}
PgxConn = conn
}
Comments