-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCREDwithMap.go
109 lines (78 loc) · 2.11 KB
/
CREDwithMap.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
package main
import (
"fmt"
"log"
"net/http"
"strconv"
)
type dollor float64
func (d dollor) String() string {
return fmt.Sprintf("$%.2f", d)
}
type database map[string]dollor
func (db database) list(w http.ResponseWriter, r *http.Request) {
for item, price := range db {
fmt.Fprintf(w, "%s: %s\n", item, price)
}
}
func (db database) delete(w http.ResponseWriter, r *http.Request) {
item := r.URL.Query().Get("item")
if _, ok := db[item]; !ok {
msg := fmt.Sprintf("Item didn't exist %q", item)
http.Error(w, msg, http.StatusBadRequest)
return
}
delete(db, item)
fmt.Fprintf(w, "Item deleted %q ", item)
}
func (db database) add(w http.ResponseWriter, r *http.Request) {
// get params from query first
// check if item exists in db, send error
// add item to db
item := r.URL.Query().Get("item")
price := r.URL.Query().Get("price")
if _, ok := db[item]; ok {
msg := fmt.Sprintf("Duplicate item %q", item)
http.Error(w, msg, http.StatusBadRequest)
return
}
p, err := strconv.ParseFloat(price, 32)
if err != nil {
msg := fmt.Sprintf("Invalid price %q %q", item, price)
http.Error(w, msg, http.StatusBadRequest)
return
}
db[item] = dollor(p)
fmt.Fprintf(w, "Item added %q with price %q", item, price)
}
func (db database) update(w http.ResponseWriter, r *http.Request) {
// get params from query first
// check if item exists in db, send error
// add item to db
item := r.URL.Query().Get("item")
price := r.URL.Query().Get("price")
if _, ok := db[item]; !ok {
msg := fmt.Sprintf("Ietm didn't exist %q", item)
http.Error(w, msg, http.StatusBadRequest)
return
}
p, err := strconv.ParseFloat(price, 32)
if err != nil {
msg := fmt.Sprintf("Invalid price %q %q", item, price)
http.Error(w, msg, http.StatusBadRequest)
return
}
db[item] = dollor(p)
fmt.Fprintf(w, "Item updated %q with price %q", item, price)
}
func main() {
db := database{
"shoe": 50,
"socks": 100,
}
http.HandleFunc("/list", db.list)
http.HandleFunc("/create", db.add)
http.HandleFunc("/delete", db.delete)
http.HandleFunc("/update", db.update)
log.Fatal(http.ListenAndServe(":8080", nil))
}