Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "github.com/gin-gonic/gin"
- "github.com/jackc/pgx"
- "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) {
- 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", limit)
- 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) {
- 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 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
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement