The endpoint to add items to the shopping cart

We declared a m variable (shown in bold), of the map[string]string type, in AddItemToShoppingCartEndpoint, which is the endpoint function that is responsible for adding a new item to the shopping cart:

func AddItemToShoppingCartEndpoint(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

We use a JSON decoder to decode the request body, which will contain a JSON encoded map sent from the client. The map will contain the SKU value of the product to add to the shopping cart, given the "productSKU" key.

We will check to see whether the shopping cart exists in the session. If it does, we will decode the shopping cart JSON data back into a ShoppingCart object:

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)
}

If the shopping cart doesn't exist, flow of control reaches the else block, and we will create a new shopping cart:

} else {
// Shopping Cart Doesn't Exist in Session, Create a New One
cart = models.NewShoppingCart()
}

We will then make a call to the AddItem method of the ShoppingCart object to add the product item:

cart.AddItem(m["productSKU"])

To add an item to our shopping cart, we simply have to provide the product's SKU value, which we can obtain from the m map variable by accessing the value that exists in the map for the productSKU key.

We will encode the cart object into its JSON representation and save it into the session, with the session key "shoppingCart":

    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"))
})

We then write back the response, "OK", to the client, to indicate that the operation to add a new item to the cart was performed successfully.

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

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