-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewwebserver.go
61 lines (50 loc) · 1.23 KB
/
newwebserver.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
package main
import (
"fmt"
"log"
"net/http"
"io/ioutil"
"encoding/json"
)
var myDict = make(map[string]string)
func printCatalog(w http.ResponseWriter) {
fmt.Fprintln(w, "Item ", "Count")
for key, value := range myDict {
fmt.Fprintln(w, key, " ", value)
}
}
func readFile() {
data, _ := ioutil.ReadFile("catalog.txt")
json.Unmarshal(data, &myDict)
}
func writeFile() {
data, _ := json.Marshal(myDict)
_ = ioutil.WriteFile("catalog.txt", data, 0644)
}
func main() {
readFile()
http.HandleFunc("/", HelloHandler)
fmt.Println("Server started at port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func HelloHandler(w http.ResponseWriter, r *http.Request) {
//fmt.Fprintln(w, r.URL.Path)
if r.URL.Path == "/catalog/add" {
handleAdd(w, r)
} else if r.URL.Path == "/catalog/list" {
handleList(w, r)
}
}
func handleAdd(w http.ResponseWriter, r *http.Request) {
//fmt.Fprintln(w, "Adding...")
item := r.URL.Query().Get("item")
count := r.URL.Query().Get("count")
if item != "" && count != "" {
myDict[item] = count
writeFile()
}
}
func handleList(w http.ResponseWriter, r *http.Request) {
//fmt.Fprintln(w, "Listing..")
printCatalog(w)
}