<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rudraksh_Nanavaty on Medium]]></title>
        <description><![CDATA[Stories by Rudraksh_Nanavaty on Medium]]></description>
        <link>https://medium.com/@rudrakshnanavaty?source=rss-2e755d3097e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gj-PdMcypgELJy0ldQLgvw.jpeg</url>
            <title>Stories by Rudraksh_Nanavaty on Medium</title>
            <link>https://medium.com/@rudrakshnanavaty?source=rss-2e755d3097e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:01:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rudrakshnanavaty/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Amazon Shopping — The Computer Engineer Way]]></title>
            <link>https://medium.com/@rudrakshnanavaty/amazon-shopping-the-computer-engineer-way-e9c0839723d1?source=rss-2e755d3097e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c0839723d1</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Rudraksh_Nanavaty]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 05:53:36 GMT</pubDate>
            <atom:updated>2023-11-26T05:53:36.974Z</atom:updated>
            <content:encoded><![CDATA[<h3>Amazon Shopping — The Computer Engineer Way</h3><p>Because I’m lazy 🥱</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*elzkZ3Uow74cichb" /></figure><h3>Introduction</h3><p>Hello 👋</p><p>Today, we will see how to shop on Amazon like a pro 😎</p><p>As a computer engineer, I always prefer automating a task for hours rather than wasting minutes doing it by hand.</p><p>So, when I found myself checking for the price of my favourite keyboard on Amazon every day, I decided to spend hours writing code that does the same rather than wasting 5 minutes every day doing it manually.</p><h3>Deciding on a Tech Stack</h3><h4>The Scraper</h4><p>I first tried using only the python requests library to get an HTML and scrape that via BeautifulSoup.</p><blockquote><em>Sorry, we just need to make sure you’re not a robot. For best results, please make sure your browser is accepting cookies.</em></blockquote><blockquote><em>~ Amazon</em></blockquote><p>So no BeautifuSoup. I had to use a web driver for automation to make Amazon think I was human. So I moved to Selenium, wrote the scraping script again, this time encountering a different error. Yay! Progress!</p><p>Using the Chrome driver, Amazon still prevented loading the pages consistently, where I could just grab the product name and price directly with its CSS selector. So move to Firefox web driver. With that, Amazon reliably displayed the content where I could just grab the first item with the class a-price and ID productTitle. (I don&#39;t need to specify which is which)</p><h4>The Server</h4><p>Since I had the web scraping script in Python, I decided to go with the same for the server. Hence, picked FastAPI. But here, I overlooked 1 thing. Python is terrible when it comes to parallelly running code. Sure, it has subprocess and schedule libraries, but that still got me stuck because schedule involves a while(True) loop for checking if any scheduled actions are pending. I could not keep that within my server, and If I start a subprocess, I need to implement a messaging queue to check whether I have a response yet. All of that was too much work, so instead, I shifted to Go for the server and parallel programming part and Python for the scraping. This way, I could write the server in Go, start a new routine, and call the Python script from there.</p><p>Hence, I finalised on:</p><ul><li>Server: Go and Gin</li><li>Scraping: Python and Selenium</li><li>Database: SQLite3 (a simple DB, nothing crazy.)</li></ul><h3>API Endpoints</h3><p>The server I made has exposed 3 routes currently:</p><ul><li>/all to get everything from the DB</li><li>/price to fetch the product price from Amazon, given the URL in the request body</li><li>/track to start tracking the product price, given the URL in the request body and notify the user in case it changes.</li></ul><p>The first 2 are just for testing purposes.</p><p>Wait, but what if I buy the product and want to stop receiving the price updates?</p><p>I plan on working on a /cancel route for the same in the future.</p><h3>The Scripts</h3><p>For the above endpoints, I needed 2 scripts.</p><ul><li>get_price.py to for /price</li><li>get_info.py to fetch product name and price to be added to the DB for each /track request</li></ul><p>Both scripts are pretty similar in their basic structure that is:</p><ul><li>Import dependencies</li><li>Initialise the Firefox web driver</li><li>Open the URL</li><li>Get the required element(s)</li><li>driver.quit</li><li>Print the required output</li></ul><p>I have logged errors in a separate file as I was scanning stdout for the final output and didn’t want error messages to mess with that.</p><h3>get_price.py</h3><pre>try:<br>    from sys import argv<br>    from selenium import webdriver<br>    from selenium.webdriver.common.by import By<br>    import logging<br>    logging.basicConfig(filename=&#39;./scripts/get_price.log&#39;, level=logging.INFO, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br>except ImportError:<br>    logging.error(&quot;Dependencies missing. Please run &#39;pip install -r ./scripts/requirements.txt&#39;&quot;)<br>    exit(1)<br><br>try:<br>    # initialise Firefox webdriver with options<br>    options = webdriver.FirefoxOptions()<br>    # don&#39;t open a window<br>    options.add_argument(&quot;-headless&quot;)<br>    driver = webdriver.Firefox(options=options)<br>except:<br>    logging.error(&quot;Error initialising Firefox webdriver.&quot;)<br>    exit(1)<br><br>try:<br>    driver.get(argv[1])<br>except:<br>    logging.error(&quot;Error fetching page from URL.&quot;)<br>    exit(1)<br><br>try:<br>    # get the price of the product<br>    price_string = driver.find_element(By.CLASS_NAME, &#39;a-price&#39;).text<br>except:<br>    logging.error(&quot;Error fetching price from URL.&quot;)<br>    exit(1)<br><br>driver.quit()<br><br>print(float(price_string.replace(&#39;₹&#39;, &#39;&#39;).replace(&#39;,&#39;, &#39;&#39;).replace(&#39;\n&#39;, &#39;.&#39;)), end=&quot;&quot;)</pre><h3>get_info.py</h3><pre>try:<br>    from sys import argv<br>    from selenium import webdriver<br>    from selenium.webdriver.common.by import By<br>    import logging<br>    logging.basicConfig(filename=&#39;./scripts/get_info.log&#39;, level=logging.INFO, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br>except ImportError:<br>    logging.error(&quot;Dependencies missing. Please run &#39;pip install -r ./scripts/requirements.txt&#39;&quot;)<br>    exit(1)<br><br>try:<br>    # initialise Firefox webdriver with options<br>    options = webdriver.FirefoxOptions()<br>    # don&#39;t open a window<br>    options.add_argument(&quot;-headless&quot;)<br>    driver = webdriver.Firefox(options=options)<br>except:<br>    logging.error(&quot;Error initialising Firefox webdriver.&quot;)<br>    exit(1)<br><br>try:<br>    driver.get(argv[1])<br>except:<br>    logging.error(&quot;Error fetching page from URL.&quot;)<br>    exit(1)<br><br>try:<br>    # get the price of the product<br>    price_string = driver.find_element(By.CLASS_NAME, &#39;a-price&#39;).text<br>    price = float(price_string.replace(&quot;₹&quot;, &quot;&quot;).replace(&quot;,&quot;, &quot;&quot;).replace(&quot;\n&quot;, &quot;.&quot;))<br>    # get product name<br>    name_string = driver.find_element(By.ID, &#39;productTitle&#39;).text<br>except:<br>    logging.error(&quot;Error fetching price from URL.&quot;)<br>    exit(1)<br><br>driver.quit()<br><br>print(f&#39;{{&quot;name&quot;: &quot;{name_string}&quot;, &quot;url&quot;: &quot;{argv[1]}&quot;, &quot;price&quot;: {price}}}&#39;)</pre><h3>Program Flow</h3><p>The user (or front end in this case) sends a POST request with a URL to start tracking a product. I then call the get_info script to add the product Name, URL and Price to the DB.</p><p>Then, I start a go routine to run the get_price script periodically. If this price changes, I notify the user accordingly.</p><p>I have also tried to stick as much as possible to the Clean Architecture I discussed in my previous <a href="https://rudrakshnanavaty.hashnode.dev/">blogs</a>.</p><h3>Key Functions</h3><p>I won’t paste the code for the entire server here, just the key components.</p><p>The entire code can be found on my GitHub.</p><p><a href="https://github.com/RudrakshNanavaty">RudrakshNanavaty - Overview</a></p><h3>main.go</h3><pre>package main<br><br>import (<br>    &quot;price-tracker/database&quot;<br>    &quot;price-tracker/handler&quot;<br>    &quot;price-tracker/router&quot;<br>)<br><br>func main() {<br>    // Initialize repository<br>    productDB := database.NewDB()<br><br>    // Initialize use case<br>    productHandler := handler.NewHandler(productDB)<br><br>    // Set up router<br>    router := router.SetupRouter(productHandler)<br><br>    // Run the server<br>    router.Run(&quot;:8080&quot;)<br>}</pre><p>Here, I have used dependency injection so that even if I switch out the implementation of one of the components, it does not affect the other components as long as the names of exported functions are consistent.</p><p>For each request, the router calls the handler, coordinating the scripting and database functions.</p><h3>Handler</h3><pre>func (h *Handler) TrackPrice(url string) (*entities.Product, error) {<br>    outputChannel := make(chan entities.Product)<br>    errorChannel := make(chan error)</pre><pre>    go fetchProductInfo(url, outputChannel, errorChannel)</pre><pre>    select {<br>    case err := &lt;-errorChannel:<br>        fmt.Println(&quot;Error fetching price&quot;)<br>        return nil, err</pre><pre>    case product := &lt;-outputChannel:<br>        h.db.AddProduct(&amp;product)</pre><pre>        go startTracking(&amp;product, h.db)</pre><pre>        return &amp;product, nil<br>    }<br>}</pre><p>Here, we can see there are 2 go routines.</p><p>fetchProductInfo gets the initial product name and price from Amazon.</p><p>If the details are found, the product is added to the DB and startTracking then periodically compares the price on Amazon to the one stored in the DB.</p><p>Since startTracking will run as a go routine, I can have a while(True) in there without halting the execution of my server.</p><h3>startTracking()</h3><pre>func startTracking(product *entities.Product, db *database.DB) {<br>    for {<br>        scriptOutputChannel := make(chan float64)<br>        scriptErrorChannel := make(chan error)<br>        dbOutputChannel := make(chan float64)<br>        dbErrorChannel := make(chan error)<br><br>        go func(outputChannel chan float64, errorChannel chan error) {<br>            newPrice, err := getProductPrice(product.URL)<br>            if err != nil {<br>                errorChannel &lt;- err<br>                return<br>            }<br>            outputChannel &lt;- newPrice<br>        }(scriptOutputChannel, scriptErrorChannel)<br><br>        go func(outputChannel chan float64, errorChannel chan error) {<br>            oldPrice, err := db.GetPrice(product.ID)<br>            if err != nil {<br>                errorChannel &lt;- err<br>                return<br>            }<br>            outputChannel &lt;- oldPrice<br>        }(dbOutputChannel, dbErrorChannel)<br><br>        select {<br>        case err := &lt;-scriptErrorChannel:<br>            fmt.Println(&quot;Error fetching price: &quot;, err)<br>            return<br><br>        case err := &lt;-dbErrorChannel:<br>            fmt.Println(&quot;Error fetching price: &quot;, err)<br>            return<br><br>        case oldPrice := &lt;-scriptOutputChannel:<br>            newPrice := &lt;-dbOutputChannel<br>            if newPrice != oldPrice {<br>                db.UpdatePrice(product.ID, newPrice)<br>                fmt.Printf(&quot;Price updated.\n%s\n%f -&gt; %f\n&quot;, product.Name, oldPrice, newPrice)<br>            }<br>        }<br>        // Sleep for a day before checking again.<br>        time.Sleep(24 * time.Hour)<br>    }<br>}</pre><p>Here, I parallelly get the current price from Amazon and the old price from the DB.</p><p>If there’s a mismatch, I notify the user (For now, just print to the console, later an E-Mail or an SMS).<br>I execute this comparison, wait a day, and then try again.</p><h3>Future Work</h3><ul><li>Implement the notification part (SMS or E-Mail)</li><li>Expose another endpoint to cancel the tracking of a product.</li></ul><h3>Check out some of my other blogs at</h3><p><a href="https://rudrakshnanavaty.hashnode.dev/">Rudraksh Nanavaty</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c0839723d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Clean Architecture in GO]]></title>
            <link>https://medium.com/@rudrakshnanavaty/implementing-clean-architecture-in-go-5f06dd8c1596?source=rss-2e755d3097e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f06dd8c1596</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rudraksh_Nanavaty]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 07:31:00 GMT</pubDate>
            <atom:updated>2023-10-14T07:40:37.712Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Clean Architecture in Go</h3><p>Because why not? 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yjl8TesacqXIaW85" /></figure><p>Hello Hi! 👋</p><p>I’m back after my exams 🥵 and ready to continue my back-end developer journey 🫡🎯</p><h3>Introduction</h3><p>In my previous blogs, we saw how we can build a web server using Go and Gin. We also saw the theoretical concepts of Clean Architecture. So how about we apply the architecture to our server now?</p><p>Sounds interesting? Let’s go!</p><p>The steps we will follow to construct the layers will be as follows:</p><ul><li>Construct the entities layer</li><li>Construct the UseCase layer by defining an interface, followed by its concrete implementation</li><li>Construct the database interface, and its concrete implementation</li><li>Set up the router to handle requests</li><li>Connect the different layers in the main.go file</li></ul><h3>Setting Up the Layers</h3><h4>Entities</h4><p>In the server we made in my first blog, we had only one entity: Person</p><p>Hence, our entity layer would have a single struct (I’m replacing person with User and people with Users).</p><p>The entities/user.go file will contain:</p><pre>package entities<br><br>// data definitions<br>type User struct {<br>    ID   string `json:&quot;id&quot;`<br>    Name string `json:&quot;name&quot;`<br>}</pre><p>(The final file/folder structure, and the GitHub link for the complete project, are at the end of the blog for reference)</p><h4>Usecase</h4><p>Steps for constructing this layer:</p><ul><li>Make a UserUseCase interface</li><li>Add the function skeletons for user actions within the interface</li><li>Build the concrete implementation within usecases/user/user.go</li></ul><pre>// usecases/usecases.go<br>// this contains all the interfaces for all usecasses<br>// (currently, only UserUseCase)<br>package usecases<br><br>import &quot;web-server/entities&quot;<br><br>type UserUseCase interface {<br>    GetAll() ([]*entities.User, error)<br>    GetByID(id string) (*entities.User, error)<br>    CreateNew(user *entities.User) error<br>}</pre><pre>// usecases/user/user.go<br>package usecases<br><br>import (<br>    &quot;web-server/database&quot;<br>    &quot;web-server/entities&quot;<br>)<br><br>// userUseCase struct contains a UserDB instance<br>type userUseCase struct {<br>    DB database.UserDB<br>}<br><br>// return UseCase object to be passed on to the Router<br>func NewUserUseCase(userRepo database.UserDB) *userUseCase {<br>    return &amp;userUseCase{<br>        DB: userRepo,<br>    }<br>}<br><br>func (uc *userUseCase) GetAll() ([]*entities.User, error) {<br>    return uc.DB.GetAll()<br>}<br><br>func (uc *userUseCase) GetByID(id string) (*entities.User, error) {<br>    return uc.DB.GetByID(id)<br>}<br><br>func (uc *userUseCase) CreateNew(user *entities.User) error {<br>    return uc.DB.CreateNew(user)<br>}</pre><h4>Database</h4><p>First, we will make a UserDB interface and write the skeletons for all the functions we need.</p><pre>// database/database.go<br>package database<br><br>import &quot;web-server/entities&quot;<br><br>type UserDB interface {<br>    GetAll() ([]*entities.User, error)<br>    GetByID(id string) (*entities.User, error)<br>    CreateNew(user *entities.User) error<br>}</pre><p>Now for concrete implementations:</p><pre>// database/users/users.go<br>package database<br><br>import &quot;web-server/entities&quot;<br><br>type UserDB struct {<br>    users []*entities.User<br>}<br><br>func NewUserDB() *UserDB {<br>    return &amp;UserDB{<br>        users: []*entities.User{<br>            {<br>                ID:   &quot;1&quot;,<br>                Name: &quot;ABC&quot;,<br>            },<br>            {<br>                ID:   &quot;2&quot;,<br>                Name: &quot;DEF&quot;,<br>            },<br>            {<br>                ID:   &quot;3&quot;,<br>                Name: &quot;GHI&quot;,<br>            },<br>        },<br>    }<br>}<br><br>func (repo *UserDB) GetAll() ([]*entities.User, error) {<br>    return repo.users, nil<br>}<br><br>func (repo *UserDB) GetByID(id string) (*entities.User, error) {<br>    for _, user := range repo.users {<br>        if user.ID == id {<br>            return user, nil<br>        }<br>    }<br>    return nil, nil // or an error indicating user not found<br>}<br><br>func (repo *UserDB) CreateNew(user *entities.User) error {<br>    repo.users = append(repo.users, user)<br>    return nil<br>}</pre><h3>Router Setup</h3><p>Now, we will make the user router, which will handle all the requests coming to /users</p><pre>// routes/users/users.go<br>package routes<br><br>import (<br>    &quot;net/http&quot;<br>    &quot;web-server/entities&quot;<br>    &quot;web-server/usecases&quot;<br>    &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func SetupRouter(userUC usecases.UserUseCase) *gin.Engine {<br>    router := gin.Default()<br><br>    // GET All Users<br>    router.GET(&quot;/users&quot;, func(c *gin.Context) {<br>        users, err := userUC.GetAll()<br><br>        if err != nil {<br>            c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to get users&quot;})<br>            return<br>        }<br>        c.IndentedJSON(http.StatusOK, users)<br>    })<br><br>    // GET User by ID<br>    router.GET(&quot;/users/:id&quot;, func(c *gin.Context) {<br>        id := c.Param(&quot;id&quot;)<br><br>        user, err := userUC.GetByID(id)<br>        if err != nil {<br>            c.IndentedJSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to get user&quot;})<br>            return<br>        }<br><br>        if user == nil {<br>            c.IndentedJSON(http.StatusNotFound, gin.H{&quot;error&quot;: &quot;User not found&quot;})<br>            return<br>        }<br><br>        c.IndentedJSON(http.StatusOK, user)<br>    })<br><br>    // POST Create New User<br>    router.POST(&quot;/users&quot;, func(c *gin.Context) {<br>        var user entities.User<br>        if err := c.ShouldBindJSON(&amp;user); err != nil {<br>            c.IndentedJSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Invalid user data&quot;})<br>            return<br>        }<br><br>        if err := userUC.CreateNew(&amp;user); err != nil {<br>            c.IndentedJSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to create user&quot;})<br>            return<br>        }<br><br>        c.Status(http.StatusCreated)<br>    })<br>    return router<br>}</pre><h3>Assembling the Pieces</h3><p>Finally, we will make the main.go file to string together all the different layers.</p><pre>package main<br><br>import (<br>    userDatabase &quot;web-server/database/users&quot;<br>    userRouter &quot;web-server/routes/users&quot;<br>    userUseCase &quot;web-server/usecases/user&quot;<br>)<br><br>func main() {<br>    // Initialize repository<br>    userDB := userDatabase.NewUserDB()<br><br>    // Initialize use case<br>    userUC := userUseCase.NewUserUseCase(userDB)<br><br>    // Set up router<br>    router := userRouter.SetupRouter(userUC)<br><br>    // Run the server<br>    router.Run(&quot;:8080&quot;)<br>}</pre><p>Here, we can see we have “injected” the dependencies when calling the constructor so that if we swap out the DB layer to let’s say a Postgres instance, then we can easily do so within just the database layer (or ./database) and the new DB implementation will then be passed on to the use case layer, and since the enforced interface is still valid, no changes should be required (if the architecture implementation is perfect 😅)</p><p>In the current state, some of the steps might seem redundant, but the goal was to attempt to replicate how we would make large-scale projects.</p><h3>File Structure</h3><p>The overall file structure of the project is:</p><pre>web-server<br>├── database<br>│   ├── users<br>│   │   └── users.go<br>│   └── database.go<br>├── entities<br>│   └── user.go<br>├── routes<br>│   └── users<br>│       └── users.go<br>├── usecases<br>│   ├── user<br>│   │   └── user.go<br>│   └── usecases.go<br>├── go.mod<br>├── go.sum<br>└── main.go<br><br>8 directories, 9 files</pre><h3>Afterword</h3><p>The End! 😅</p><p>I was planning on connecting PostgreSQL to the server instead of an in-memory DB within the same blog but then decided to split it into two.</p><p>So stay tuned! 😄</p><h3>Appendix</h3><p>The full code with a few tweaks, some more functions, etc. is uploaded on my <a href="https://github.com/RudrakshNanavaty/Go_Gin_Server">GitHub</a>.</p><p>The previous blogs mentioned:</p><ul><li><a href="https://medium.com/@rudrakshnanavaty/building-a-web-server-using-go-and-gin-39150b8304ee">Building a Web Server using Go and Gin</a></li><li><a href="https://medium.com/@rudrakshnanavaty/clean-architecture-7c1b3b4cb181">Clean Architecture</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f06dd8c1596" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture]]></title>
            <link>https://medium.com/@rudrakshnanavaty/clean-architecture-7c1b3b4cb181?source=rss-2e755d3097e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c1b3b4cb181</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Rudraksh_Nanavaty]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 12:53:00 GMT</pubDate>
            <atom:updated>2023-10-13T12:54:47.506Z</atom:updated>
            <content:encoded><![CDATA[<p>Because nothing stands the test of time ⏱</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ATAHRV0taZm5ieM" /></figure><h3>Foreword</h3><p>Hello, fellow experimenters! 👋</p><p>Welcome to my Lab! 🧪</p><p>In today’s experiment, we’re gonna be looking at Clean Architecture. 😄</p><p>As developers, we’re always told to stay up-to-date and learn new things. But then we run into old code that’s about as flexible as petrified wood. 🪵 Enter Robert Cecil Martin, or “Uncle Bob” with his Clean Architecture! 💪</p><p>When I initially came across this, I decided to use the same approach that I have been following in my Design Pattern class, since this too seemed like a really popular design pattern. I took an existing implementation and tried to match it with the concepts I learn. I soon found out that this wasn’t gonna work here. Gotta come up with something else. So I decided to try another approach. I had read somewhere that to truly understand a concept, I had to answer the 5 ‘W’s and an ‘H’. The What Why, Who, Where, When and How. I already mentioned the Who, and in this case, the When and Where is not important. So in this blog, we’ll see:</p><ul><li><strong>What</strong> is Clean Architecture?</li><li><strong>How</strong> does it work?</li><li><strong>Why</strong> go through all that trouble?</li></ul><h3>What?</h3><p>Clean Architecture revolves around a simple idea. Structuring your code in the form of layers, with each layer having its specific purpose (Single Responsibility Principle or SRP). It starts from the inner layer and gradually moves out towards the outermost layer. In Clean Architecture, the dependencies move inward. This means that the outer layers are dependent on the layer directly below them, but the inner layers do not depend on any of the outer layers. Hence, the innermost layer does not depend on anything.</p><p>Think of it like an onion.🧅 With outermost layers that can easily be peeled off, without damaging any of its insides. Similarly, in Clean Architecture, the outermost layers are the ones that change most frequently, but since none of the inner layers depends on it, they can easily be swapped out and replaced.</p><p>If you found this analogy confusing, maybe you will better understand the one from <a href="https://pusher.com/tutorials/clean-architecture-introduction/">pusher.com</a> where they tie objects with tangled strings and try to replace one of them (the scissors).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Gi5akfP329V54Ssq.jpeg" /><figcaption>A dependency mess</figcaption></figure><p>As you can see in the picture above, replacing the scissors without disturbing any of the others is difficult. But, if we re-structure it into something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*u0Be1PsMXcmBKcIf.jpeg" /><figcaption>The mess ‘managed’ centrally</figcaption></figure><p>Now, we can just take the string attached to the scissors out from under the Post-it box, and put another one in there. None of the others will be disturbed. Here it seems as if all entities are related to a single central entity, however, that is not necessary for Clean Architecture.</p><p>The actual representation of it, as proposed by “Uncle Bob” includes 4 concentric circles, a diagram which you would be familiar with if you had even tried to read about the architecture before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*0a3SRm_70D1R8ela.jpg" /><figcaption>Uncle Bob’s Clean Architecture diagram</figcaption></figure><p>Here, as discussed earlier, are 4 layers, with the arrows representing dependencies. We don’t necessarily need to have 4 layers, we can have fewer, or more depending on the scale and complexity of our application. Next, we will look at each layer and discuss what it could contain.</p><h4>Entity</h4><p>The entity layer is at the lowest level of abstraction and is the backbone of your entire system. It does not depend on any other layer, and houses entities that are the fundamental building blocks of the application. Abstract things like classes, interfaces etc. make up this layer.</p><p>For example, if we have a User class or a post interface, it should not be dependent on any other logic of the software like the Database or Framework used or any other logic in the code. Similarly, only things in the “use case” layer should be dependent directly on the “entity” or “domain” layer. Now what exactly lies in the “use case” layer?</p><h4>Use Case</h4><p>The use case layer is where all the important business logic of your application lives. Think of it as the master chef who takes raw ingredients and creates a delicious meal. 🍳👨‍🍳 In this case, the raw ingredients are the request data received from the controller layer, and the meal is the object created from that data.</p><p>For example, if you want to register a new user, the use case layer takes the request data and creates a user object from it. Once the object is created, it passes it on to the infrastructure layer, which handles the database implementation to store it.</p><p>So, the use case layer is like the middleman between the controller and infrastructure layers, ensuring that all the business logic is properly executed and implemented.</p><h4>Controller</h4><p>The controller layer is like the traffic cop of your application.🚦 It’s responsible for managing the flow of incoming requests and directing them to the appropriate destination. Just like a traffic cop, the controller layer needs to be quick and efficient, making sure that each request is properly validated and passed on to the right place. It is also responsible for adapting the incoming request data, and parsing and validating it for further use. So if the incoming data is of invalid format like if someone put an invalid date (to say they were born in 1894 😉), then the error would not propagate further, and an error response would be sent back.</p><h4>Infrastructure</h4><p>The infrastructure layer is mainly responsible for storing and retrieving data from the database. 📚 Think of it as the librarian, who makes sure that each piece of information is properly organized and easy to access. It sometimes also interacts with external services like payment gateways or email providers.</p><h4>Outermost</h4><p>The outermost layer typically consists of the UI. So for a back-end developer, the controller is the outermost implementation. The UI built by the front-end developer is the outermost in most cases. Like the peel of the Clean Architecture onion. 🧅</p><p>All the inner layers are independent of it. The back end could receive requests from a Web App, a Mobile app, or even something like Postman, it would work the same in all cases.</p><h3>How?</h3><p>Another question that might arise is: if the use case implements business logic to for example add a user to the database, then doesn’t this inherently mean that the use case would depend on the database or infrastructure layer? How do we fix that? We say that the use case implements logic but it doesn’t depend on the database, or the framework used for getting the data to perform that logic. How exactly is that possible?</p><p>Well, the actual implementation we’ll hopefully see in upcoming blogs, but we can discuss the logic behind it here. In the example above, yes the use case depends on the other layers. But that’s where a concept called dependency inversion comes into the picture. It is here to turn the tables (or dependencies) and invert them to our favourable direction (inwards rather than outwards).</p><h4>Dependency Inversion 🔃</h4><p>Dependency Inversion is one method that is key to implementing Clean Architecture. Suppose we have 2 entities: A and B. Let’s say A depends on B, but we want it the other way around. In that case, we can introduce an abstract interface C between them to act as an Uno Reverse Card. 🔃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*N375qU9Sezs14wYN" /></figure><p>I have tried to illustrate what I am saying in the picture above. Here, initially, Entity A depended on another Entity B. To invert this dependency, we introduced an interface C, which enforces the format of output that is accepted by A. So no matter what the inside logic is, if any entity follows this interface, then it can be used by A to perform its task. Hence, A no longer depends specifically on B, but B has to comply with the rules accepted by A. Hence, B has now become dependent on A. Now, if A was the use case and B was a database connection like Postgre, that can easily be replaced as long as the newer implementation fulfils the format enforced by C.</p><p>So now if the application scales up and the data becomes so highly relational that a relational database like Neo4j would be more feasible, the only changes required would be within B.</p><p>As long as the output implements C, we can even feed a stub instead of C for testing purposes. 🧪</p><p>Congrats! 🥳 Your code is now highly flexible 🤸, maintainable, testable and modular!</p><p>Go ahead! show off all this jargon and impress some clients! 😎</p><p>Next, we’ll see another method for solving dependency conflicts called <em>dependency injection</em>.</p><h4>Dependency Injection 💉</h4><p>Dependency Injection to resolve dependency conflicts involves passing the dependency from an external source, rather than importing it first-hand. Like when you buy a remote, it depends on the batteries to work. When TV companies include the batteries with the remote, they inject that dependency, so that you don’t explicitly have to import (buy) them. This is an effective technique used to decouple code in Clean Architecture.</p><p>With this, one layer could call a method in another layer, without actually knowing about the concrete implementation within that layer. A common way to achieve this is by passing an object of the other layer into the parameters of methods of the first layer. The dependent layer could then call the methods of that object without worrying about the concrete implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cyoqx3oOIlu5wfiD" /></figure><p>Hence, whenever we decide to upgrade the code of the dependency, as long as the method names are the same and they provide similar functionality, any dependent layer can call those methods and continue working as before. This could also help stub out the dependency for testing purposes. For example: shifting to a local in-memory database for testing.</p><h3>Why?</h3><p>Ok. Now that we know the What and How of Clean Architecture, it’s high time we asked Why? Why go through the whole process of implementing such a sophisticated architecture?</p><ul><li>For starters, the number one aspect of development that a lot of people seem to forget quite often:</li></ul><blockquote><em>YOU’RE NOT THE ONLY ONE WORKING ON THAT CODE!!!</em></blockquote><blockquote><em>~ Literally every good developer ever</em></blockquote><p>A modular code can help teamwork as you don’t have to worry about what the other team members are doing or how you should change your code to support their implementation. You could simply focus on your part of the project, or <em>“your layer”.</em></p><ul><li>Second, as I pointed out throughout the article, your code becomes <strong><em>easier to test</em></strong>. You can easily stub out parts of the code as and when required.</li><li>Third and most important: <strong><em>Nothing stands the test of time!</em></strong> ⏱</li><li>We are not alien to deprecated dependencies and legacy code that is no longer maintained. Hence, proper implementation of Clean Architecture obviates the arduousness of migrating or upgrading i̶f̶ when required.</li></ul><p>I hope that’s enough reason for those building large, scalable projects that they hope to maintain for a long time.</p><p>Another concern is for the small-scale projects that even if deployed, will not be for handling a lot of users or data. Things like portfolio pages, simple CRUD apps made for learning and exploring, etc. These projects might never leverage the full potential of Clean Architecture in their lifetime. Hence, it would be redundant rather than optimal for such smaller projects.</p><p>Remember, Clean Architecture is not a silver bullet. It’s not a set of rules that you must follow blindly, rather it’s a set of guidelines that you can adapt and adjust to fit your specific needs and requirements.</p><p>So, one should always consider the scale and purpose of their projects before deciding what technologies and approaches to employ.</p><h3>Afterword</h3><p>Congratulations on making it to the end! 🎉</p><p>I hope reading this blog was as insightful for you as it was for me.</p><p>I will now take your leave. See you after my exams. 👋</p><p>Hopefully, after the exams, I shall attempt to implement Clean Architecture in Go.</p><p>Until then, as always, feel free to reach out in case of suggestions or doubts, I am always open to feedback and happy to help. 😇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c1b3b4cb181" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Web Server using GO and Gin]]></title>
            <link>https://medium.com/@rudrakshnanavaty/building-a-web-server-using-go-and-gin-39150b8304ee?source=rss-2e755d3097e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/39150b8304ee</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Rudraksh_Nanavaty]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 12:40:22 GMT</pubDate>
            <atom:updated>2024-03-10T06:19:56.638Z</atom:updated>
            <content:encoded><![CDATA[<p>Because PHP is a Dinosaur 🦖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y6aBqwZE_50dduN5" /></figure><h3>Introduction</h3><p>Hello 👋</p><p>This blog documents my process of building a web server with Go and Gin.</p><p>For those of you who have no idea what a web server is: It is simply a server that receives requests (mostly HTTP/HTTPS) from a client and sends back an appropriate response. For those of you who need further elaboration, why even bother coming here? Don’t pretend you didn’t read the title before clicking.</p><h3>Why GO and Gin?</h3><p>There are multiple popular web frameworks for building servers in different languages. Following are the reasons why I did not build my server in any of those:</p><ul><li>JavaScript — It was primarily built as a front-end scripting language, later adapted for the back end as well (probably because the devs were too lazy to learn a new language 😜)</li><li>Python — Initially designed for code readability, currently most popular in Data Science, Mathematics and popular general-purpose choice owing to the plethora of libraries and frameworks at our disposal. I wanted something that was specifically built for scalable efficient back-end applications.</li><li>PHP — This one doesn’t need explaining 🦖 (Why isn’t it extinct already?)</li><li>Rust — Pretty good, but still needs improvements (And did I mention the learning curve?)</li></ul><p>Enough about why I didn’t pick a popular language, why I did pick Go because it is designed specifically for building efficient and scalable software, with blazing-fast run times and a garbage collector for memory safety. In Google’s own words:</p><blockquote><em>Go is an open source, strongly typed, compiled language written </em><strong><em>to build concurrent and scalable software</em></strong><em>. Go is designed for simple, reliable, and efficient software.</em></blockquote><blockquote><em>~ </em><a href="https://developers.google.com/learn/topics/go"><em>https://developers.google.com/learn/topics/go</em></a></blockquote><p>As to why I used Gin? Well, I googled “go web frameworks” and Gin was at the top of every list I could find 😅</p><p>Also, did I mention lightweight and fast?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vhgWlyyLhaFcRZ7N" /></figure><h3>Installing GO</h3><p>I am using Fedora 37 so the installation process is quite straightforward. It is just a single command:</p><pre>sudo dnf install golang</pre><p>You can also refer to <a href="https://developer.fedoraproject.org/tech/languages/go/go-installation.html">https://developer.fedoraproject.org/tech/languages/go/go-installation.html</a> for more details regarding Go installation in Fedora.</p><p>And for those of you using other Linux distros or even Windows (I have no idea why you would prefer that), you can follow this link for the installation process: <a href="https://go.dev/doc/install">https://go.dev/doc/install</a></p><h3>Project Initialisation</h3><pre>mkdir web-server &amp;&amp; cd web-server<br>go mod init github.com/RudrakshNanavaty/go-web-server<br>touch main.go<br>code . &amp;&amp; exit<br></pre><ul><li>The first command makes an empty folder called web-server and changes the working directory to the new folder.</li><li>The second command initialises a skeletal Go project with a go.mod file using github.com/RudrakshNanavaty/go-web-server as the module path.</li><li>(I am hoping you would have some basic knowledge of Go. I am not explaining much about what the module path is for, valid module paths, etc.)</li><li>The third command creates anempty main.go file that will house the code for our server. Although modular code is preferred for bigger projects, ours is simple enough to be contained within a single file.</li><li>The fourth command is optional, it opens VSCode and exits the terminal. You may use any editor. (I use VSCode with the official GO Language Extension)</li></ul><p>Now that we have the skeleton, we can start working by writing the go boilerplate in the main.go file we created.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>   fmt.Println(&quot;Hello, World!&quot;)<br>}</pre><p>Next, to use the Gin framework, we need to add it to our project. Open the terminal in your project directory and enter:</p><pre>go get github.com/gin-gonic/gin</pre><p>After the command runs, we can see the changes in the go.mod file. Now go ahead and import Gin in your code. Change the import statement we wrote earlier to:</p><pre>import (<br>    &quot;fmt&quot;<br>    &quot;net/http&quot;<br>    &quot;github.com/gin-gonic/gin&quot;<br>)</pre><p>Notice the other net/http import. We don’t need to install anything specific for that, it’s built-in. It will be used to send HTTP statuses with the server’s responses.</p><p>Our web server is successfully initialised at this point, and <strong>go run .</strong> shouldn’t give any errors. Next, we’ll create data items to be sent when a request is sent.</p><h3>Creating Data Items</h3><pre>// data definitions<br>type person struct {<br>    ID   string `json:&quot;id&quot;`<br>    Name string `json:&quot;name&quot;`<br>}<br><br>// people slice to seed record person data.<br>var people = []person{<br>    {<br>        ID:   &quot;1&quot;,<br>        Name: &quot;ABC&quot;,<br>    },<br>    {<br>        ID:   &quot;2&quot;,<br>        Name: &quot;DEF&quot;,<br>    },<br>    {<br>        ID:   &quot;3&quot;,<br>        Name: &quot;GHI&quot;,<br>    },<br>}</pre><p>Here, we first define the struct to represent a single person, having his ID and Name. <strong>`json:”xyz”`</strong> specifies how the variable will be represented in a JSON. Next, we make a slice called people (not an array because we want to append data when a POST request is made) containing 3 sample person instances. This array will serve as the database for our server.</p><p>Ideally, a database service like PostgreSQL or MongoDB is connected and data is stored within that, but our application is small enough and we don’t need persistent data for now so I have declared person and people as global variables outside of the main function.</p><h3>Setting Up Gin in the Project</h3><pre>func main() {<br>    // a gin router to handle requests<br>    var router *gin.Engine = gin.Default()<br>    // insert request handlers<br>    // Listen at http://localhost:8080<br>    router.Run(&quot;:8080&quot;)<br>}</pre><ul><li>The <strong>gin.Default()</strong> function returns a pointer to a <strong>gin.Engine</strong> instance. This will be used to handle the HTTP requests and responses.</li><li>Also, I will manually define types wherever possible instead of using <strong>:=</strong> even though it is a great feature of Go as we are still learning and the extra information could help us understand better. Feel free to use <strong>:=</strong> if you disagree.</li><li><strong>router.Run()</strong> specifies where the server will be hosted. Here, <strong>:8080</strong> is the same as <strong>localhost:8080</strong></li></ul><h3>Request Handlers</h3><h4>GET All Items</h4><p>Next, bind the GET getPeople() function to the HTTP GET method on the /people route. getPeople() takes a pointer to a gin.Context instance and responds with the people slice as an IndentedJSON (basically a better-looking JSON) and an HTTP 200 (OK). Use the net/http we imported earlier for the response and HTTP status.</p><pre>func main() {<br>    // -- snip --<br>    router.GET(&quot;/people&quot;, getPeople)<br>    // -- snip --<br>}<br><br>// respond with the entire people struct as JSON<br>func getPeople(context *gin.Context) {<br>    // IndentedJSON makes it look better<br>    context.IndentedJSON(http.StatusOK, people)<br>}</pre><p>The gin.Context is a struct provided by Gin to represent the context of an HTTP request and response. We didn’t explicitly pass the variable because the context handler we created takes care of that.</p><h4>POST an Item</h4><p>Next, we bind the postPeople() function to the POST methods on /people to add a newPerson to the people slice.</p><pre>func main() {<br>    // -- snip --<br>    router.GET(&quot;/people&quot;, getPeople)<br>    router.POST(&quot;/people&quot;, postPeople)<br>    // -- snip --<br>}<br>// -- snip --<br>// add a person to people from JSON received in the request body<br>func postPeople(context *gin.Context) {<br>    var newPerson person<br>    // BindJSON to bind the received JSON to newPerson<br>    if err := context.BindJSON(&amp;newPerson); err != nil {<br>        // log the error, respond and return<br>        fmt.Println(err)<br>        context.IndentedJSON(http.StatusBadRequest, gin.H{<br>            &quot;message&quot;: &quot;Invalid request&quot;,<br>        })<br>        return<br>    }<br>    // append the new person to people<br>    people = append(people, newPerson)<br>    // respond as IndentedJSON<br>    context.IndentedJSON(http.StatusCreated, newPerson)<br>}</pre><p>First, we declare a variable called newPerson, then bind the received JSON to that variable. <strong>BindJSON()</strong> returns an error if it is unable to convert to received JSON to a person instance.</p><ul><li>Here we use an if block to log the error (if any) and stop further function execution.</li><li>If the received JSON is bound successfully, we append the new person to people and respond 200 (OK)</li></ul><h4>GET a Specific Item</h4><p>Now, we bind getPersonByID() to GET methods on /people/:id. The function responds with an IndentedJSON of the person whose ID is in the request params, or a 404 status if the person doesn’t exist in the slice.</p><pre>func main() {<br>    // -- snip --<br>    router.GET(&quot;/people&quot;, getPeople)<br>    router.POST(&quot;/people&quot;, postPeople)<br>    router.GET(&quot;/people/:id&quot;, getPersonByID)<br>    // -- snip --<br>}<br><br>// -- snip --<br><br>// locate the person whose ID value matches the id sent<br>// then return that person as a response<br>func getPersonByID(context *gin.Context) {<br>    // get the id from request params<br>    var id string = context.Param(&quot;id&quot;)<br><br>    // Linear Search through people<br>    for _, p := range people {<br>        // respond and return if ID matched<br>        if p.ID == id {<br>            context.IndentedJSON(http.StatusOK, p)<br>            return<br>        }<br>    }<br><br>    // respond 404<br>    context.IndentedJSON(<br>        http.StatusNotFound,<br>        // refer https://pkg.go.dev/github.com/gin-gonic/gin#H<br>        gin.H{<br>            &quot;message&quot;: &quot;person not found&quot;,<br>        },<br>    )<br>}</pre><ul><li>Declare a string id and store the “id” value from request params.</li><li>Then, Linear Search through people to find the person whose ID matches. Linear Search because we don&#39;t have a lot of data currently, and the focus is on building a working server, not optimising search. Typically, the database service would handle the search.</li><li>If the ID matches, respond with the person and return.</li><li>Else, respond 404 (Not Found)</li></ul><h3>Running and Testing</h3><p>Finally! We’ve created endpoints for users to be able to access our data! Now it’s time to put our work to the test. Since the project is small, we are not writing tests and will just manually run and test out code.</p><p>Open a terminal in your project directory and run <strong>go run .</strong></p><pre>cd web-server<br>go run .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rUxkQoziQdgc3CSS" /></figure><p>If your output is like my output in the image above, Congrats 🥳</p><p>Your code didn’t panic. Now go ahead and send a request to test if you get your desired response. This time, I am using curl to make requests.</p><p>Send a GET request to the specified path. To do that, open a new terminal window and type in:</p><pre>curl http://localhost:8080/people</pre><p>In our case, the response should be a JSON form of the people slice. Something like:</p><pre>[<br>    {<br>        &quot;id&quot;: &quot;1&quot;,<br>        &quot;name&quot;: &quot;ABC&quot;<br>    },<br>    {<br>        &quot;id&quot;: &quot;2&quot;,<br>        &quot;name&quot;: &quot;DEF&quot;<br>    },<br>    {<br>        &quot;id&quot;: &quot;3&quot;,<br>        &quot;name&quot;: &quot;GHI&quot;<br>    }<br>]</pre><p>If your output is similar to what is shown above, Congrats! One of the three handlers you made works.</p><p>Now test for the next handler.</p><pre>curl http://localhost:8080/albums \<br>    --include \<br>    --header &quot;Content-Type: application/json&quot; \<br>    --request &quot;POST&quot;\<br>    --data &#39;{&quot;id&quot;: &quot;4&quot;,&quot;name&quot;: &quot;Rudraksh&quot;}&#39;<br>curl http://localhost:8080/people</pre><p>The first command should output:</p><pre>HTTP/1.1 201 Created<br>Content-Type: application/json; charset=utf-8<br>Date: Sat, 08 Apr 2023 16:01:04 GMT<br>Content-Length: 41</pre><pre>{<br>    &quot;id&quot;: &quot;4&quot;,<br>    &quot;name&quot;: &quot;Rudraksh&quot;<br>}</pre><p>And the second:</p><pre>[<br>    {<br>        &quot;id&quot;: &quot;1&quot;,<br>        &quot;name&quot;: &quot;ABC&quot;<br>    },<br>    {<br>        &quot;id&quot;: &quot;2&quot;,<br>        &quot;name&quot;: &quot;DEF&quot;<br>    },<br>    {<br>        &quot;id&quot;: &quot;3&quot;,<br>        &quot;name&quot;: &quot;GHI&quot;<br>    },<br>    {<br>        &quot;id&quot;: &quot;4&quot;,<br>        &quot;name&quot;: &quot;Rudraksh&quot;<br>    },<br>    {<br>        &quot;id&quot;: &quot;4&quot;,<br>        &quot;name&quot;: &quot;Rudraksh&quot;<br>    },<br>    {<br>        &quot;id&quot;: &quot;4&quot;,<br>        &quot;name&quot;: &quot;Rudraksh&quot;<br>    }<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*Ah67ZArEGD-EgfcV" /></figure><p>Once again, I have pasted my output for reference, yours may vary if your data creation was different, or if you made any other changes in the code I provided.</p><p>Assuming your output was correct, now only the last handler is left for testing.</p><p>In a new terminal window, write:</p><pre>curl http://localhost:8080/people/2</pre><p>Output:</p><pre>{<br>    &quot;id&quot;: &quot;2&quot;,<br>    &quot;name&quot;: &quot;DEF&quot;<br>}</pre><p>My output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*PT4eH1XDMyAtn8aC" /></figure><p>If all of your outputs are perfectly fine and produce the desired output, then Congratulations! We have successfully built a web server using Go and Gin 🥳🎯</p><p>Now, if you notice in the terminal window where your server is running, you will notice there are readymade logs for all the requests we just sent! Cool 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1gEy86ZC5Mn9sqiu" /></figure><p>And would you look at those response times?!! Damn, they’re FAST!</p><p>Ignore the 404 in the image. I sent requests to the wrong routes 😅</p><h3>Conclusion</h3><p>Phew! Finally made it to the end of my first blog! 🎉</p><p>I feel exhausted, but also excited to have taken on this challenge and learned so much along the way. 💻💪</p><p>I hope my blog was easy to follow and understand, and that you found it useful! 😊 But, now it’s your turn to let me know what you think. 👀 Was it a hit or a miss? Leave your thoughts and feedback in the comments. Please don’t hesitate to be frank and give honest feedback. I promise I won’t cry too much 😜</p><p>I’m looking forward to hearing from you all, and can’t wait to discuss more tech with you in the future! 🤓 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39150b8304ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>