-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
230 lines (189 loc) · 6.43 KB
/
api.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"goji.io"
"goji.io/pat"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const database string = "base"
const collection string = "articles"
func ErrorWithJSON(w http.ResponseWriter, message string, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
fmt.Fprintf(w, "{message: %q}", message)
}
func ResponseWithJSON(w http.ResponseWriter, json []byte, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
w.Write(json)
}
type Article struct {
Articulo string `json:"articulo"`
Descrip string `json:"descrip"`
Original string `json:"original"`
Precio string `json:"precio"`
Foto string `json:"foto"`
Comentario string `json:"comentario"`
Marca string `json:"marca"`
Modelos string `json:"modelos"`
Motores string `json:"motores"`
}
func main() {
//MONGO DB
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
ensureIndex(session)
//Endpoitns API
mux := goji.NewMux()
//Articulos
mux.HandleFunc(pat.Get("/articles"), allArticles(session))
mux.HandleFunc(pat.Get("/articles/:articulo"), articleByCodigo(session))
mux.HandleFunc(pat.Post("/articles"), addArticle(session))
mux.HandleFunc(pat.Put("/articles/:articulo"), updateArticle(session))
mux.HandleFunc(pat.Delete("/articles/:articulo"), deleteArticle(session))
//Web Server
http.ListenAndServe("localhost:8099", mux)
}
func ensureIndex(s *mgo.Session) {
session := s.Copy()
defer session.Close()
c := session.DB(database).C(collection)
index := mgo.Index{
Key: []string{"articulo"},
Unique: true,
DropDups: true,
Background: true,
Sparse: true,
}
err := c.EnsureIndex(index)
if err != nil {
panic(err)
}
}
func allArticles(s *mgo.Session) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
session := s.Copy()
defer session.Close()
c := session.DB(database).C(collection)
var articles []Article
err := c.Find(bson.M{}).All(&articles)
if err != nil {
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed get all articles: ", err)
return
}
respBody, err := json.MarshalIndent(articles, "", " ")
if err != nil {
log.Fatal(err)
}
ResponseWithJSON(w, respBody, http.StatusOK)
}
}
func articleByCodigo(s *mgo.Session) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
session := s.Copy()
defer session.Close()
articulo := pat.Param(r, "articulo")
c := session.DB(database).C(collection)
var article Article
err := c.Find(bson.M{"articulo": articulo}).One(&article)
if err != nil {
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed find article: ", err)
return
}
if article.Articulo == "" {
ErrorWithJSON(w, "Article not found", http.StatusNotFound)
return
}
respBody, err := json.MarshalIndent(article, "", " ")
if err != nil {
log.Fatal(err)
}
ResponseWithJSON(w, respBody, http.StatusOK)
}
}
func addArticle(s *mgo.Session) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
session := s.Copy()
defer session.Close()
var article Article
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&article)
if err != nil {
ErrorWithJSON(w, "Incorrect body", http.StatusBadRequest)
return
}
c := session.DB(database).C(collection)
err = c.Insert(article)
if err != nil {
if mgo.IsDup(err) {
ErrorWithJSON(w, "Article with this code already exists", http.StatusBadRequest)
return
}
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed insert article: ", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Location", r.URL.Path+"/"+article.Articulo)
w.WriteHeader(http.StatusCreated)
}
}
func updateArticle(s *mgo.Session) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
session := s.Copy()
defer session.Close()
articulo := pat.Param(r, "articulo")
var article Article
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&article)
if err != nil {
ErrorWithJSON(w, "Incorrect body", http.StatusBadRequest)
return
}
c := session.DB(database).C(collection)
err = c.Update(bson.M{"articulo": articulo}, &article)
if err != nil {
switch err {
default:
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed update article: ", err)
return
case mgo.ErrNotFound:
ErrorWithJSON(w, "Article not found", http.StatusNotFound)
return
}
}
w.WriteHeader(http.StatusNoContent)
}
}
func deleteArticle(s *mgo.Session) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
session := s.Copy()
defer session.Close()
article := pat.Param(r, "article")
c := session.DB(database).C(collection)
err := c.Remove(bson.M{"article": article})
if err != nil {
switch err {
default:
ErrorWithJSON(w, "Database error", http.StatusInternalServerError)
log.Println("Failed delete article: ", err)
return
case mgo.ErrNotFound:
ErrorWithJSON(w, "Article not found", http.StatusNotFound)
return
}
}
w.WriteHeader(http.StatusNoContent)
}
}