The endpoint to remove items from the shopping cart

Here's the source listing of RemoveItemFromShoppingCartEndpoint, the endpoint that is responsible for removing all items of a specific product from the shopping cart:

func RemoveItemFromShoppingCartEndpoint(env *common.Env) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

igwSession, _ := env.Store.Get(r, "igweb-session")
decoder := json.NewDecoder(r.Body)
var m map[string]string
err := decoder.Decode(&m)
if err != nil {
log.Print("Encountered error when attempting to decode json data from request body: ", err)
}
defer r.Body.Close()

var cart *models.ShoppingCart
if _, ok := igwSession.Values["shoppingCart"]; ok == true {
// Shopping Cart Exists in Session
decoder := json.NewDecoder(strings.NewReader(string(igwSession.Values["shoppingCart"].([]byte))))
err := decoder.Decode(&cart)
if err != nil {
log.Print("Encountered error when attempting to decode json data from session: ", err)
}
} else {
// Shopping Cart Doesn't Exist in Session, Create a New One
cart = models.NewShoppingCart()
}

for k, v := range cart.Items {
if v.ProductSKU == m["productSKU"] {
delete(cart.Items, k)
}
}

b := new(bytes.Buffer)
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(b).Encode(cart)
if err != nil {
log.Print("Encountered error when attempting to encode cart struct as json data: ", err)
}
igwSession.Values["shoppingCart"] = b.Bytes()
igwSession.Save(r, w)

w.Write([]byte("OK"))

})
}

Remember that we can have multiple quantities for a given product. In the current shopping cart implementation, if the user clicks on the Remove From Cart button, the given product (and all quantities of it) are removed from the shopping cart.

We start out by fetching the JSON encoded shopping cart data from the session. If it exists, we decode the JSON object into a new ShoppingCart object. If the shopping cart does not exist in the session, we simply create a new shopping cart.

We range through the items found in the shopping cart, and if we are able to find a product in the cart containing the same product SKU code supplied in the m map variable that was obtained from the client-side web application, we will remove the element from the shopping cart object's Items map by calling the built-in delete function (shown in bold). Finally, we will write out a JSON encoded response to the client that the operation was successfully completed.

Now that we have our server-side endpoints in place, it's time to take a look at the functionality needed on the client side to implement the final pieces of the shopping cart feature.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.44.229