The endpoint to get the list of products

Let's examine the products.go source file in the endpoints folder:

package endpoints

import (
"encoding/json"
"net/http"

"github.com/EngineerKamesh/igb/igweb/common"
)

func GetProductsEndpoint(env *common.Env) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
products := env.DB.GetProducts()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(products)
})
}

Inside the GetProductsEndpoint function, we first fetch the slice of products that will be displayed on the client-side products page by calling the GetProducts method of the datastore object, env.DB. We then set a header to indicate that the server response will be in JSON format. Finally, we use a JSON encoder to encode the slice of products as JSON data and write it out using the the http.ResponseWriter, w.

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

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