Create a Simple Shopping Cart Service with Go – I

I want to create a simple shopping cart service with go lang.First of all,I’ll create a very simple domain model for shopping cart except any bounded context like items,details etc.

I use constants for Status and TypeCode fields like

So, i created a very simple domain model for shopping cart.And now, I ll create a handler for create,update,delete or other implementations.

Before I began create handlers , I ll write a generic json response and error functions.A basic response function

And a basic error function

I created a simple error and response functions.and now, i will create a createCart function.

I ll try to explain the above code line by line.

First of all, I created a cart object like var cart Cart

And then I read request body and assing body to cart object like json.NewDecoder(r.Body).Decode(&cart)

And then check assigned object required properties like UserId etc.

if cart.UserId == “” { JSONError(w, r, start, “Incorrect body”, http.StatusBadRequest) return }

After that I created a bson object and save to mongodb.

If any exception occured i try to set http status as 500.

if err != nil { JSONError(w, r, start, “Failed to create cart”, http.StatusInternalServerError) return }

By the way, I use mongodb as db provider.And i used the following code block for the database connection

You can define connection yaml and store your connection string, collection name, db name etc. at configuration file but i did not want to worry about it.

At this point ,i created a sample domain model, handlers and db connection provider.And now, I ll define a routing for my handlers like

I used NotFound for undefined routings.

Finally, I created a main function like that

And the curl request

 

Ill write and implement update and delete handlers in the next article.

 

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *