This repository has been archived by the owner on Jul 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 277
/
bookstore.go
161 lines (139 loc) · 4.45 KB
/
bookstore.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
package main
import (
"encoding/json"
"flag"
"fmt"
"html"
"html/template"
"math/rand"
"net/http"
"os"
"strings"
"sync/atomic"
"time"
"github.com/gorilla/mux"
"github.com/openservicemesh/osm/demo/cmd/common"
"github.com/openservicemesh/osm/pkg/logger"
)
var (
books common.BookStorePurchases
log = logger.NewPretty("bookstore")
identity = flag.String("ident", "unidentified", "the identity of the container where this demo app is running (VM, K8s, etc)")
port = flag.Int("port", 14001, "port on which this app is listening for incoming HTTP")
path = flag.String("path", ".", "path to the HTML template")
)
type handler struct {
path string
fn func(http.ResponseWriter, *http.Request)
method string
}
func getIdentity() string {
ident := os.Getenv("IDENTITY")
if ident == "" {
if identity != nil {
ident = *identity
}
}
return ident
}
func setHeaders(w http.ResponseWriter, r *http.Request) {
w.Header().Set(common.BooksBoughtHeader, fmt.Sprintf("%d", books.BooksSold))
w.Header().Set(common.IdentityHeader, getIdentity())
if r != nil {
for _, header := range common.GetTracingHeaders() {
if v := r.Header.Get(header); v != "" {
w.Header().Set(header, v)
}
}
}
}
func renderTemplate(w http.ResponseWriter) {
tmpl, err := template.ParseFiles(fmt.Sprintf("%s/bookstore.html.template", *path))
if err != nil {
log.Fatal().Err(err).Msg("Failed to parse HTML template file")
}
err = tmpl.Execute(w, map[string]string{
"Identity": getIdentity(),
"BooksSold": fmt.Sprintf("%d", books.BooksSold),
"Time": time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST"),
})
if err != nil {
log.Fatal().Err(err).Msg("Could not render template")
}
}
func getBooksSold(w http.ResponseWriter, r *http.Request) {
setHeaders(w, r)
renderTemplate(w)
log.Info().Msgf("%s; URL: %q; Count: %d\n", getIdentity(), html.EscapeString(r.URL.Path), books.BooksSold)
}
func getIndex(w http.ResponseWriter, r *http.Request) {
setHeaders(w, r)
renderTemplate(w)
log.Info().Msgf("%s; URL: %q; Count: %d\n", getIdentity(), html.EscapeString(r.URL.Path), books.BooksSold)
}
// updateBooksSold updates the booksSold value to the one specified by the user
func updateBooksSold(w http.ResponseWriter, r *http.Request) {
var updatedBooksSold int64
err := json.NewDecoder(r.Body).Decode(&updatedBooksSold)
if err != nil {
log.Fatal().Err(err).Msg("Could not decode request body")
}
atomic.StoreInt64(&books.BooksSold, updatedBooksSold)
setHeaders(w, r)
renderTemplate(w)
log.Info().Msgf("%s; URL: %q; %s: %d\n", getIdentity(), html.EscapeString(r.URL.Path), common.BooksBoughtHeader, books.BooksSold)
}
// sellBook increments the value of the booksSold
func sellBook(w http.ResponseWriter, r *http.Request) {
fmt.Println("Selling a book!")
atomic.AddInt64(&books.BooksSold, 1)
setHeaders(w, r)
renderTemplate(w)
log.Info().Msgf("%s; URL: %q; Count: %d\n", getIdentity(), html.EscapeString(r.URL.Path), books.BooksSold)
// Loop through headers
for name, headers := range r.Header {
name = strings.ToLower(name)
for _, h := range headers {
log.Info().Msgf("%v: %v", name, h)
}
}
go common.RestockBooks(1) // make this async for a smoother demo
// Slow down the responses artificially.
maxNoiseMilliseconds := 750
minNoiseMilliseconds := 150
intNoise := rand.Intn(maxNoiseMilliseconds-minNoiseMilliseconds) + minNoiseMilliseconds // #nosec G404
pretendToBeBusy := time.Duration(intNoise) * time.Millisecond
log.Info().Msgf("Sleeping %+v", pretendToBeBusy)
time.Sleep(pretendToBeBusy)
}
func getHandlers() []handler {
return []handler{
{"/", getIndex, "GET"},
{"/books-bought", getBooksSold, "GET"},
{"/books-bought", updateBooksSold, "POST"},
{"/buy-a-book/new", sellBook, "GET"},
{"/reset", reset, "GET"},
{"/liveness", ok, "GET"},
{"/raw", common.GetRawGenerator(&books), "GET"},
{"/readiness", ok, "GET"},
{"/startup", ok, "GET"},
}
}
func reset(w http.ResponseWriter, _ *http.Request) {
books.BooksSold = 0
renderTemplate(w)
}
func ok(w http.ResponseWriter, _ *http.Request) {
renderTemplate(w)
}
func main() {
flag.Parse()
router := mux.NewRouter()
for _, h := range getHandlers() {
router.HandleFunc(h.path, h.fn).Methods(h.method)
}
http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {})
log.Info().Msgf("Bookstore running on port %d", *port)
err := http.ListenAndServe(fmt.Sprintf(":%d", *port), router)
log.Fatal().Err(err).Msgf("Failed to start HTTP server on port %d", *port)
}