Commit 7bd57fb0 authored by rima anggraini's avatar rima anggraini

udah terstruktur ya

parent 617ac106
package main
//initial Connection ke DB
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func connect() (*sql.DB, error) {
db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/test")
if err != nil {
return nil, err
}
fmt.Println(db)
return db, nil
}
...@@ -10,53 +10,6 @@ import ( ...@@ -10,53 +10,6 @@ import (
_ "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql"
) )
type student struct {
ID string
Name string
Grade int
}
type product struct {
ProductID uint64
ProductName string
Stock int
}
type Response struct {
Status int `json:"status"`
Message string `json:"message"`
Data []product
}
type productCategory struct {
ProductID int
ProductName string
Stock int
}
type category struct {
CategoryID int
CategoryName string
}
type CategoryArr struct {
CategoryName string
DataProduct []productCategory
}
type ResponseCategory struct {
Status string
Message string
data CategoryArr
}
var data = []student{
student{"E001", "ethan", 21},
student{"W001", "wick", 22},
student{"B001", "bourne", 23},
student{"B002", "bond", 23},
}
func users(w http.ResponseWriter, r *http.Request) { func users(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
...@@ -75,16 +28,6 @@ func users(w http.ResponseWriter, r *http.Request) { ...@@ -75,16 +28,6 @@ func users(w http.ResponseWriter, r *http.Request) {
http.Error(w, "", http.StatusBadRequest) http.Error(w, "", http.StatusBadRequest)
} }
func connect() (*sql.DB, error) {
db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/test")
if err != nil {
return nil, err
}
fmt.Println(db)
return db, nil
}
func user(w http.ResponseWriter, r *http.Request) { func user(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
...@@ -143,9 +86,11 @@ func products(w http.ResponseWriter, r *http.Request) { ...@@ -143,9 +86,11 @@ func products(w http.ResponseWriter, r *http.Request) {
log.Print(err) log.Print(err)
} }
for rows.Next() { for rows.Next() {
//buat model sesuai field yang diselect
if err := rows.Scan(&products.ProductID, &products.ProductName, &products.Stock); err != nil { if err := rows.Scan(&products.ProductID, &products.ProductName, &products.Stock); err != nil {
log.Fatal(err.Error()) log.Fatal(err.Error())
} else { } else {
//put product ke array
arr_product = append(arr_product, products) arr_product = append(arr_product, products)
} }
} }
...@@ -161,11 +106,17 @@ func products(w http.ResponseWriter, r *http.Request) { ...@@ -161,11 +106,17 @@ func products(w http.ResponseWriter, r *http.Request) {
http.Error(w, "", http.StatusBadRequest) http.Error(w, "", http.StatusBadRequest)
} }
func categoryfunc(w http.ResponseWriter, r *http.Request) { func insertProduct(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
if r.Method == "POST" { if r.Method == "POST" {
var productName = r.FormValue("product_name")
var stock = r.FormValue("stock")
var category = r.FormValue("category_id")
var response Response
db, err := connect() db, err := connect()
if err != nil { if err != nil {
fmt.Println(err.Error()) fmt.Println(err.Error())
...@@ -175,45 +126,107 @@ func categoryfunc(w http.ResponseWriter, r *http.Request) { ...@@ -175,45 +126,107 @@ func categoryfunc(w http.ResponseWriter, r *http.Request) {
defer db.Close() defer db.Close()
fmt.Println("OK") fmt.Println("OK")
var productsresult productCategory fmt.Println("==============" + productName)
var arrayProduct []productCategory
var response ResponseCategory _, err = db.Exec("INSERT INTO Product (ProductName, Stock, CategoryID) values (?,?,?)",
productName,
productCategory, err := db.Query("select ProductID, ProductName, Stock from Product WHERE CategoryID = 1") stock,
category,
fmt.Println("-----------------") )
if err != nil { if err != nil {
log.Print(err) log.Print(err)
} }
for productCategory.Next() {
if err := productCategory.Scan(productsresult.ProductID, productsresult.ProductName, productsresult.Stock); err != nil { response.Status = 1
log.Fatal(err.Error()) response.Message = "Success Insert Data"
} else { w.Header().Set("Content-Type", "application/json")
arrayProduct = append(arrayProduct, productsresult) json.NewEncoder(w).Encode(response)
} }
http.Error(w, "", http.StatusBadRequest)
}
func checkCount(rows *sql.Rows) (count int) {
for rows.Next() {
err := rows.Scan(&count)
checkErr(err)
} }
return count
}
fmt.Println("Masuk sini---------") func checkErr(err error) {
var datacat = CategoryArr{ if err != nil {
CategoryName: "Makanan", panic(err)
DataProduct: arrayProduct,
} }
}
response.Status = "OK" func updateProduct(w http.ResponseWriter, r *http.Request) {
response.Message = "Success"
response.data = datacat
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
if r.Method == "POST" {
var productName = r.FormValue("product_name")
var stock = r.FormValue("stock")
var category = r.FormValue("category_id")
var productId = r.FormValue("product_id")
var ResponseCRUD ResponseCRUD
db, err := connect()
if err != nil {
fmt.Println(err.Error())
return
}
defer db.Close()
fmt.Println("OK")
rows, err := db.Query("select COUNT(ProductID) as count from Product WHERE ProductID = " + productId)
if err != nil {
fmt.Println(err.Error())
return return
} }
defer rows.Close()
if checkCount(rows) > 0 {
fmt.Println("==============" + productName)
_, err = db.Exec("UPDATE Product Set ProductName = ?, Stock = ?, CategoryID = ? Where ProductID = ? ",
productName,
stock,
category,
productId,
)
if err != nil {
log.Print(err)
} else {
ResponseCRUD.Status = 1
ResponseCRUD.Message = "Success Update Data"
ResponseCRUD.DataProduct = productId
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ResponseCRUD)
}
} else {
ResponseCRUD.Status = 0
ResponseCRUD.Message = "Data Not Found"
ResponseCRUD.DataProduct = productId
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ResponseCRUD)
}
}
http.Error(w, "", http.StatusBadRequest) http.Error(w, "", http.StatusBadRequest)
} }
func sqlQuery() { func categoryfunc(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method == "POST" {
db, err := connect() db, err := connect()
if err != nil { if err != nil {
fmt.Println(err.Error()) fmt.Println(err.Error())
...@@ -223,46 +236,64 @@ func sqlQuery() { ...@@ -223,46 +236,64 @@ func sqlQuery() {
defer db.Close() defer db.Close()
fmt.Println("OK") fmt.Println("OK")
//var productsresult Category
var products product
var arrayProduct []product
var response ResponseCategory
rows, err := db.Query("select ProductID, ProductName, Stock from Product") rows, err := db.Query("select ProductID, ProductName, Stock from Product")
//rows, err := db.Query("select ProductID, ProductName, Stock from Product WHERE CategoryID = 1")
if err != nil { if err != nil {
fmt.Println(err.Error()) fmt.Println(err.Error())
return return
} }
defer rows.Close() defer rows.Close()
var result []product //productCategory, err := db.Query("select ProductID, ProductName, Stock from Product WHERE CategoryID = 1")
for rows.Next() { fmt.Println("-----------------")
var each = product{}
var err = rows.Scan(&each.ProductID, &each.ProductName, &each.Stock)
if err != nil { if err != nil {
fmt.Println(err.Error()) log.Print(err)
return }
for rows.Next() {
if err := rows.Scan(products.ProductID, products.ProductName, products.Stock); err != nil {
log.Fatal(err.Error())
} else {
arrayProduct = append(arrayProduct, products)
}
} }
result = append(result, each) fmt.Println("Masuk sini---------")
var datacat = CategoryArr{
CategoryName: "Makanan",
DataProduct: arrayProduct,
} }
if err = rows.Err(); err != nil { response.Status = "OK"
fmt.Println(err.Error()) response.Message = "Success"
response.data = datacat
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
return return
} }
for _, each := range result { http.Error(w, "", http.StatusBadRequest)
fmt.Println(each.ProductName)
}
} }
func main() { func main() {
//ini route yang di panggil di postman
http.HandleFunc("/users", users) http.HandleFunc("/users", users)
http.HandleFunc("/user", user) http.HandleFunc("/user", user)
http.HandleFunc("/product", products) http.HandleFunc("/product", products)
http.HandleFunc("/category", categoryfunc) http.HandleFunc("/category", categoryfunc)
http.HandleFunc("/insertproduct", insertProduct)
http.HandleFunc("/updateproduct", updateProduct)
sqlQuery() //initial url yang di panggil di postman
fmt.Println("starting web server at http://localhost:8080/") fmt.Println("starting web server at http://localhost:8080/")
http.ListenAndServe(":8080", nil) http.ListenAndServe(":8080", nil)
......
package main package main
type Products struct { //initial model yang di panggil di main api
Id int64 `form:"id" json:"ProductId"` type student struct {
ProductName string `form:"firstname" json:"Productname"` ID string
Stock int `form:"lastname" json:"Stock"` Name string
Grade int
} }
type product struct {
ProductID uint64 `json:"ProductID"`
ProductName string
Stock int
}
type Response struct { type Response struct {
Status int `json:"status"` Status int `json:"status"`
Message string `json:"message"` Message string `json:"message"`
Data []Products Data []product
}
type ResponseCRUD struct {
Status int `json:"status"`
Message string `json:"message"`
DataProduct string
}
type Category struct {
ProductID string `json:"ProductID"`
ProductName string `json:"ProductName"`
Stock int `json:"Stock"`
}
type CategoryArr struct {
CategoryName string
DataProduct []product
}
type ResponseCategory struct {
Status string
Message string
data CategoryArr
}
var data = []student{
student{"E001", "ethan", 21},
student{"W001", "wick", 22},
student{"B001", "bourne", 23},
student{"B002", "bond", 23},
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment