-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
163 lines (117 loc) · 3.34 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
// Estructura de un producto
type Product struct {
ID int `json:"ID"`
Name string `json:"Name"`
Price int `json:"Price"`
Brand string `json:"Brand"`
}
// Arreglo de todos los productos
type AllProducts []Product
// Varible con todos los productos
var products = AllProducts{
{
ID: 1,
Name: "Laptop",
Price: 20000,
Brand: "HP",
},
}
// Handler para la ruta principal
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Hello Shop</h1")
}
// Handler para mostrar los productos
func getProducts(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(products)
}
// Handler para crear un producto
func createProduct(w http.ResponseWriter, r *http.Request) {
// Almcenamos el cuerpo de la peticion en una variable
reqBody, err := ioutil.ReadAll(r.Body)
//Comprobamos si hay un error
if err != nil {
log.Fatal(err)
}
// Creamos una varible de tipo procucto
var newProduct Product
// Hacemos que el ID sea autoincrementable
newProduct.ID = len(products) + 1
//Convertimos el cuerpo de la peticion en un objeto y lo almacenamos en la variable newProduct
json.Unmarshal(reqBody, &newProduct)
// Agregamos el nuevo producto al arreglo de productos
products = append(products, newProduct)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newProduct)
}
// Handler para buscar un producto
func searchProduct(w http.ResponseWriter, r *http.Request) {
// Obtenemos las variables de la ruta
vars := mux.Vars(r)
productId, err := strconv.Atoi(vars["id"])
if err != nil {
fmt.Fprintf(w, "Invalid Id")
}
for _, p := range products {
if p.ID == productId {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusFound)
json.NewEncoder(w).Encode(p)
}
}
}
// Handler para eliminar un producto
func delteProduct(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
productId, err := strconv.Atoi(vars["id"])
if err != nil {
fmt.Fprintf(w, "Invalid Id")
}
for i, p := range products {
if p.ID == productId {
products = append(products[:i], products[1+1:]...)
fmt.Fprintf(w, "The product with ID %v has been deleted", productId)
}
}
}
func updateProduct(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
productId, err := strconv.Atoi(vars["id"])
if err != nil {
fmt.Fprintf(w, "Invalid ID")
}
var updateProduct Product
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
json.Unmarshal(reqBody, &updateProduct)
for i, p := range products {
if p.ID == productId {
products = append(products[:i], products[1+i:]...)
updateProduct.ID = productId
w.Header().Set("Content-Type", "application/json")
products = append(products, updateProduct)
}
}
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", handler)
router.HandleFunc("/products", getProducts).Methods("GET")
router.HandleFunc("/products", createProduct).Methods("POST")
router.HandleFunc("/products/{id}", searchProduct).Methods("GET")
router.HandleFunc("/products/{id}", delteProduct).Methods("DELETE")
router.HandleFunc("/products/{id}", updateProduct).Methods("PUT")
http.ListenAndServe(":8080", router)
}