-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
76 lines (60 loc) · 1.42 KB
/
main.go
File metadata and controls
76 lines (60 loc) · 1.42 KB
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
package main
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
)
// ItemList : list of items
type ItemList []struct {
Item string `json:"item"`
}
func main() {
http.HandleFunc("/items", items)
http.HandleFunc("/count", count)
http.HandleFunc("/", health)
http.HandleFunc("/health", health)
http.ListenAndServe(":8080", nil)
}
func items(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "[{\"item\":\"apple\"}, {\"item\":\"orange\"}, {\"item\":\"pear\"}]\n")
}
func health(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "{\"message\":\"OK\"}\n")
}
func count(w http.ResponseWriter, r *http.Request) {
url := os.Getenv("ITEMS_SERVICE_URL") + "/items"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
io.WriteString(w, url)
io.WriteString(w, " connect error\n")
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
io.WriteString(w, url)
io.WriteString(w, " error executing request\n")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
io.WriteString(w, url)
io.WriteString(w, " error reading response\n")
return
}
var i ItemList
err = json.Unmarshal(body, &i)
if err != nil {
io.WriteString(w, url)
io.WriteString(w, " error reading response\n")
return
}
s := strconv.Itoa(len(i))
io.WriteString(w, "{\"count\":\"")
io.WriteString(w, s)
io.WriteString(w, "\"}\n")
}