@@ -53,8 +53,19 @@ type staticFile struct {
5353 contentType string
5454}
5555
56+ type RawItem struct {
57+ ID int `json:"id"`
58+ Name string `json:"name"`
59+ Category string `json:"category"`
60+ Price float64 `json:"price"`
61+ Quantity int `json:"quantity"`
62+ Active bool `json:"active"`
63+ Tags []string `json:"tags"`
64+ Rating Rating `json:"rating"`
65+ }
66+
5667type Handler struct {
57- jsonResponse [] byte
68+ dataset [] RawItem
5869 jsonLargeResponse []byte
5970 staticFiles map [string ]staticFile
6071 db * sql.DB
@@ -77,29 +88,9 @@ func (h *Handler) Provision(ctx caddy.Context) error {
7788 return nil // dataset not available, /json will 500
7889 }
7990
80- var dataset []struct {
81- ID int `json:"id"`
82- Name string `json:"name"`
83- Category string `json:"category"`
84- Price float64 `json:"price"`
85- Quantity int `json:"quantity"`
86- Active bool `json:"active"`
87- Tags []string `json:"tags"`
88- Rating Rating `json:"rating"`
89- }
90- if err := json .Unmarshal (data , & dataset ); err != nil {
91+ if err := json .Unmarshal (data , & h .dataset ); err != nil {
9192 return nil
9293 }
93- items := make ([]ProcessedItem , len (dataset ))
94- for i , d := range dataset {
95- items [i ] = ProcessedItem {
96- ID : d .ID , Name : d .Name , Category : d .Category ,
97- Price : d .Price , Quantity : d .Quantity , Active : d .Active ,
98- Tags : d .Tags , Rating : d .Rating ,
99- Total : math .Round (d .Price * float64 (d .Quantity )* 100 ) / 100 ,
100- }
101- }
102- h .jsonResponse , _ = json .Marshal (ProcessResponse {Items : items , Count : len (items )})
10394
10495 // Load large dataset for /compression
10596 largeData , err := os .ReadFile ("/data/dataset-large.json" )
@@ -186,11 +177,21 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
186177 return nil
187178
188179 case "/json" :
189- if h .jsonResponse != nil {
180+ if h .dataset != nil {
181+ items := make ([]ProcessedItem , len (h .dataset ))
182+ for i , d := range h .dataset {
183+ items [i ] = ProcessedItem {
184+ ID : d .ID , Name : d .Name , Category : d .Category ,
185+ Price : d .Price , Quantity : d .Quantity , Active : d .Active ,
186+ Tags : d .Tags , Rating : d .Rating ,
187+ Total : math .Round (d .Price * float64 (d .Quantity )* 100 ) / 100 ,
188+ }
189+ }
190+ resp , _ := json .Marshal (ProcessResponse {Items : items , Count : len (items )})
190191 w .Header ().Set ("Content-Type" , "application/json" )
191192 w .Header ().Set ("Server" , "caddy" )
192- w .Header ().Set ("Content-Length" , strconv .Itoa (len (h . jsonResponse )))
193- w .Write (h . jsonResponse )
193+ w .Header ().Set ("Content-Length" , strconv .Itoa (len (resp )))
194+ w .Write (resp )
194195 } else {
195196 http .Error (w , "No dataset" , 500 )
196197 }
0 commit comments