The endpoint to get items in the shopping cart

Let's examine the shopping cart's Rest API endpoints, which help service actions that the client-side web application is dependent on. Let's start with the endpoint function, GetShoppingCartItemsEndpoint, which is responsible for getting the items in the shopping cart. The Encode step, of the isomorphic handoff procedure is performed in this endpoint function.

Here's the source listing of the GetShoppingCartItemsEndpoint function:

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

var cart *models.ShoppingCart
igwSession, _ := env.Store.Get(r, "igweb-session")

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

products := env.DB.GetProductsInShoppingCart(cart)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(products)

} else {
// Shopping cart doesn't exist in session
cart = nil
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(cart)
return
}

})
}

In this function, we fetch the shopping cart from the session. If we are able to successfully fetch the shopping cart from the session, we use a JSON encoder to encode the ShoppingCart object and write it using http.ResponseWriter, w.

If the shopping cart does not exist in the session, then we simply JSON encode the value of nil (which is equivalent to a JavaScript null on the client side) and write it out in the response, using http.ResponseWriter, w.

With this code in place, we have fulfilled the Encode step in the isomorphic handoff procedure.

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

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