<?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 Yashasree Tummala on Medium]]></title>
        <description><![CDATA[Stories by Yashasree Tummala on Medium]]></description>
        <link>https://medium.com/@tummalayashasree?source=rss-1c90556dc21c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-qSvWCt2bg6GQCpC2vgmWg.jpeg</url>
            <title>Stories by Yashasree Tummala on Medium</title>
            <link>https://medium.com/@tummalayashasree?source=rss-1c90556dc21c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:17:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tummalayashasree/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[From Chaos to Control: Who Manages Your Web Traffic?]]></title>
            <link>https://medium.com/@tummalayashasree/from-chaos-to-control-who-manages-your-web-traffic-79acbe38908e?source=rss-1c90556dc21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/79acbe38908e</guid>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[devops-engineer]]></category>
            <dc:creator><![CDATA[Yashasree Tummala]]></dc:creator>
            <pubDate>Tue, 13 May 2025 11:53:15 GMT</pubDate>
            <atom:updated>2025-05-13T11:53:15.241Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever found yourself tangled in the terminology of <strong>Load Balancers, Reverse Proxies, Forward Proxies, and API Gateways </strong>— wondering if they all do the same thing but in different hats? You’re not alone.</p><p>In this post, I’ll break them down <em>from a hands-on developer and infrastructure enthusiast’s point of view</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEqBTiCEkpWYyOFuVHZPWw.gif" /><figcaption>Found this on the internet and I need not redo the same</figcaption></figure><h4>1. Load Balancer 🧭— Your traffic controller</h4><p><strong>What it does:</strong><br>Distributes traffic across multiple servers to ensure no single one gets overwhelmed.</p><p><strong>Use it when:<br></strong>You have multiple instances of a service<br>You want high availability and reliability<br>You’re horizontally scaling apps</p><blockquote>A traffic cop stands at a busy junction and directs cars to different roads to avoid congestion. That’s your load balancer managing incoming traffic across servers.</blockquote><h4>2. Reverse Proxy 🔁— The shield behind your apps</h4><p><strong>What it does:</strong><br>Sits between client and server, handles incoming requests, and forwards them to the right internal service.</p><p><strong>Use it when:<br></strong>You want to hide internal architecture<br>Offload SSL or handle caching<br>Act as a smart dispatcher</p><blockquote><em>It’s like a receptionist who takes your request and routes it to the correct office, while keeping internal offices private.</em></blockquote><h4>3. Forward Proxy 🚪— Your gateway to the internet</h4><p><strong>What it does:</strong><br>Used by clients to access external sites anonymously or with control, say VPN, (filtering, logging).</p><p><strong>Use it when:<br></strong>You want to restrict outbound access<br>Enforce browsing policies<br>Add anonymity to users</p><blockquote>Imagine you’re staying at a hotel, and instead of calling room service yourself, you ask the concierge to do it for you. Room service only sees the concierge’s number, not yours. That’s what a proxy does — it makes the request on your behalf and hides your identity.</blockquote><h4>4. API Gateway 🚦— The single entry point for your APIs</h4><p><strong>What it does:</strong><br>Fronts all your microservices, handles routing, rate limiting, security, and more.</p><p><strong>Use it when:<br></strong>You have microservices exposing APIs<br>Need central control over traffic/authentication<br>Want to manage versioning and analytics</p><blockquote>A receptionist at a company doesn’t do all the work, but directs you to the right department, logs your visit, and even checks if you’re allowed. That’s what an API gateway does for incoming API calls.</blockquote><h3>Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fls4Yhq_QiE5IHv5qs-7hA.png" /><figcaption>Comparision table</figcaption></figure><h3>Conclusion💡</h3><p>Understanding the subtle yet critical differences between these components helps not only in <strong>building scalable and secure systems</strong> but also in <strong>aceing system design interviews</strong> and making better architectural decisions.</p><p>So the next time someone throws these terms around in a meeting, you’ll know exactly who does what — and more importantly, when to use which.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79acbe38908e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying DNS: The Internet’s Invisible Guide]]></title>
            <link>https://medium.com/@tummalayashasree/demystifying-dns-the-internets-invisible-guide-7bbacdbbc867?source=rss-1c90556dc21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bbacdbbc867</guid>
            <dc:creator><![CDATA[Yashasree Tummala]]></dc:creator>
            <pubDate>Tue, 06 May 2025 10:35:39 GMT</pubDate>
            <atom:updated>2025-05-07T04:20:57.565Z</atom:updated>
            <content:encoded><![CDATA[<p>Through many interviews I’ve taken, I realized one common thing — most freshers had no clue how the internet really works. Their answers were often surprisingly funny — and definitely unexpected!, and that’s what motivated me to write this blog!<br>If you’ve ever typed something like <a href="http://www.instagram.com/">www.instagram.com</a> and wondered how your browser instantly shows the website, you’re about to find out. The hidden hero behind this smooth experience is something called the Domain Name System, or DNS.</p><p>In this post, I’ll walk you through how DNS works and why it’s such an important part of the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcaQDtDk5pO364tcAnEIww.png" /></figure><p>🌐 <strong>What is DNS?</strong><br>At its core, DNS (Domain Name System) is like a massive, distributed phonebook for the internet. While humans remember names like google.com, computers need IP addresses like 192.168.1.1 to locate and communicate with each other. DNS serves as the translator between these two worlds.</p><p>In short: <strong>DNS converts domain names into IP addresses</strong>, enabling your browser to find and load the right content on the web.</p><p><strong>Why Do We Need DNS? 🤔</strong><br>Here’s what makes DNS so crucial:</p><ul><li><strong>Human Convenience</strong>: People remember names like google.com, not IP addresses like 142.250.72.206. DNS allows us to use readable names instead of complex numbers.</li><li>Network Efficiency: Computers need IP addresses to route traffic. DNS quickly resolves these names to IPs, keeping web browsing fast and seamless.</li><li><strong>Scalability</strong>: The internet hosts <strong>billions of domain names</strong>. DNS provides a <strong>distributed system</strong> that handles this massive load efficiently.</li><li><strong>Flexibility</strong>: DNS allows websites to change their IP address (e.g., during a server migration) <strong>without changing the domain name</strong>. Users don’t need to know the change; the updated IP is resolved behind the scenes.</li><li><strong>Load Balancing &amp; Redundancy:</strong> DNS can point a single domain name to <strong>multiple IP addresses</strong>, helping with: Load balancing, Geographic routing, Failover and high availability.</li><li><strong>Security (with DNSSEC, DoH, etc.):</strong> Extensions like <strong>DNSSEC</strong> (DNS Security Extensions) and <strong>DoH</strong> (DNS over HTTPS) make DNS more secure and private. <em>DNS has also evolved to be more secure. </em><strong>DNSSEC</strong> protects against DNS spoofing by digitally signing responses. <strong>DoH (DNS over HTTPS)</strong> encrypts DNS queries to prevent eavesdropping by ISPs or attackers.</li></ul><blockquote>📄 <strong>Common DNS Records (And What They Do)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eo-48fRMP-_ii3nMe8X9zA.png" /><figcaption>Types of DNS records.</figcaption></figure><p>DNS isn’t just a one-size-fits-all lookup — it uses various record types to handle different needs:<br>Okay, here’s a brief overview of common DNS (Domain Name System) records with examples.</p><p>DNS records are like instructions in a phone book for the internet. They tell computers how to find a specific domain or how to handle services related to that domain.<br>Here are some of the most common types:</p><ol><li><strong>A Record (Address Record)<br>Purpose:</strong> Maps a domain name (or subdomain) to an IPv4 address (e.g., 192.0.2.1). This is the most fundamental record type for reaching a website.<br><strong>Example:<br></strong>Domain: example.com<br>Record Type: A<br>Value/Points to: 93.184.216.34<br><em>Meaning: When you type </em><em>example.com in your browser, it should go to the server at IP address </em><em>93.184.216.34.</em></li><li><strong>AAAA Record (IPv6 Address Record)<br>Purpose:</strong> Similar to an A record, but maps a domain name to an IPv6 address (a newer, longer IP address format, e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334).<br><strong>Example:<br></strong>Domain: example.com<br>Record Type: AAAA<br>Value/Points to: 2606:2800:220:1:248:1893:25c8:1946<br><em>Meaning: For systems using IPv6, </em><em>example.com points to this IPv6 address.</em></li><li><strong>CNAME Record (Canonical Name Record)<br>Purpose:</strong> Maps an alias name (a subdomain) to another true or canonical domain name. It’s used to point one domain or subdomain to another. You can’t have a CNAME record for a root domain (e.g., example.comitself).<br><strong>Example:<br></strong>Alias/Domain: <a href="http://www.example.com/">www.example.com</a><br>Record Type: CNAME<br>Value/Points to: example.com<br><em>Meaning: </em><em>www.example.com is an alias for </em><em>example.com. If </em><em>example.com&#39;s A record changes, </em><em>www.example.com will automatically point to the new address.</em></li><li><strong>NS Record (Name Server Record)<br>Purpose:</strong> Specifies the authoritative DNS servers for the domain. These are the servers that hold all the DNS records for that particular domain.<br><strong>Example:<br></strong>Domain: example.com<br>Record Type: NS<br>Value/Points to: ns1.nameserverprovider.com<br><em>Meaning: </em><em>ns1.nameserverprovider.com is one of the authoritative name servers for </em><em>example.com.<br></em>Typically, a domain will have at least two NS records for redundancy.</li><li><strong>MX Record (Mail Exchange Record)<br>Purpose:</strong> Specifies the mail server(s) responsible for receiving email messages on behalf of a domain name. It includes a priority value (lower number means higher priority).<br><strong>Example:<br></strong>Domain: example.com<br>Record Type: MX<br>Priority: 10<br>Value/Points to: mail.example.com<br><em>Meaning: Emails sent to </em><em>@example.com addresses should be delivered to the server </em><em>mail.example.comwith a priority of 10.<br></em>You might have multiple MX records, e.g.:<br>Priority: 20, Value: mail-backup.example.com</li><li><strong>TXT Record (Text Record)<br>Purpose:</strong> Allows a domain administrator to store arbitrary text information. Often used for verification purposes (like proving domain ownership to Google or Microsoft), for SPF (Sender Policy Framework) records to combat email spoofing, or DKIM (DomainKeys Identified Mail) signatures.</li><li><strong>SOA Record (Start of Authority Record)<br>Purpose:</strong> Provides authoritative information about the DNS zone, including the primary name server, email of the domain administrator, domain serial number, 1 and timers relating to refreshing the zone. 2 Every DNS zone needs an SOA record.</li></ol><p>These are the core DNS records you’ll encounter most frequently. There are others like SRV (Service) records for specific services, PTR (Pointer) records for reverse DNS lookups, CAA (Certification Authority Authorization) records, etc., but the ones above are the essentials.</p><blockquote>⚙️ <strong>Behind the Scenes: How DNS Works (Step by Step)</strong><br>Let’s say you open a browser and enter www.instagram.com. What happens next?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGi6O36YxyARTJnf2gpTDQ.png" /></figure><ol><li><strong>You Make a Request (Browser &amp; OS Cache Check)</strong></li></ol><ul><li>Your <strong>browser</strong> first checks if it already knows the IP address from a previous visit.</li><li>If not, it asks the <strong>operating system (OS)</strong>.<br>The OS checks:<br>Its own DNS cache.<br>The <strong>hosts file</strong> (a manual list of domain-to-IP mappings).</li></ul><p>✅ If the IP address is found at any of these local stages, the process jumps to step 9 (Website Loads), and no network request for DNS is needed.</p><p><strong>2. Ask the DNS Recursive Resolver (If Not Found Locally):</strong></p><ul><li>If the IP isn’t found locally, your computer sends a query asking, “What’s the IP for www.instagram.com?” to a DNS recursive resolver (often called a &quot;DNS recursor&quot;). This resolver is typically provided by your Internet Service Provider (ISP), but could also be a third-party one you&#39;ve configured (like Google&#39;s 8.8.8.8 or Cloudflare&#39;s 1.1.1.1).</li></ul><p><strong>3</strong>. <strong>Resolver Cache Check:</strong></p><ul><li>The recursive resolver first checks its own cache to see if it already has the IP address for www.instagram.com stored from a previous query it handled (perhaps for another user). If it does and the record hasn&#39;t expired (based on its TTL - Time To Live), it returns the IP directly to your computer (jump to step 8).</li><li><strong>Note:</strong> TTL (Time To Live) defines how long a DNS response should be cached. For example, if www.instagram.com has a TTL of 300 seconds, your browser will reuse the IP for 5 minutes before querying again.</li></ul><p>4. <strong>Ask the Root Server (If Not in Resolver’s Cache):</strong></p><ul><li>If the IP is not cached by the resolver, it kicks off a multi-step <em>iterative query process</em>.</li><li>The resolver queries one of the internet’s <a href="https://www.iana.org/domains/root/servers"><strong><em>Root DNS servers</em></strong></a>. Root servers don’t know the IP for www.instagram.com, but they know where to find the servers that manage the .com <strong>top-level domain (TLD)</strong>. The root server responds with the address of a .com TLD server.</li></ul><p>5. <strong>Ask the TLD Server:</strong></p><ul><li>Next, the resolver queries one of the .com TLD servers (using the address it got from the root server). The TLD server doesn&#39;t know the IP for www.instagram.com itself, but it knows the authoritative DNS servers for the instagram.com domain. The TLD server responds with the addresses of instagram.com’s authoritative name servers.</li></ul><p>6. <strong>Authoritative Answer:</strong></p><ul><li>The resolver now queries one of instagram.com&#39;s authoritative name servers (using an address it got from the TLD server). This authoritative server <em>does</em> know the IP address (or other record types). It looks up www.instagram.comin its zone files.</li><li>It finds the A record (for IPv4) or AAAA record (for IPv6) which contains the IP address. (Note: www.instagram.com might first be a CNAME record pointing to another name like star.c10r.instagram.com, in which case the resolver would then have to resolve <em>that</em> name, possibly repeating steps 4-6 for that new name until an A/AAAA record is found).</li><li>The authoritative server sends this IP address back to the recursive resolver.</li></ul><p>7. <strong>Resolver Caches and Responds:</strong></p><ul><li>The recursive resolver receives the IP address for www.instagram.com</li><li>It caches this IP address (along with its TTL) so it can answer future requests for www.instagram.com more quickly.</li><li>The resolver then sends the IP address back to your computer’s OS.</li></ul><p>8. <strong>Back to Browser:</strong></p><ul><li>Your OS receives the IP address and passes it to the browser. The browser uses it to connect to Instagram’s web server using <strong>HTTP/HTTPS protocols</strong>. The OS also caches this information.</li></ul><p>9. <strong>Website Loads:</strong></p><ul><li>Armed with the IP address, your browser can now establish a direct connection (TCP/IP) to the server hosting www.instagram.com. After connection, standard web protocols (HTTP/HTTPS) are used to request and display the webpage. Voilà, Instagram appears!</li></ul><p>🛠️ <strong>Try it Yourself<br></strong> You can explore DNS records using tools like:<br>nslookup <a href="http://www.instagram.com/">www.instagram.com</a><br>dig <a href="http://www.instagram.com/">www.instagram.com</a><br>These show the IP addresses and DNS records behind the scenes.</p><p>🛠️ <strong>Common DNS Issue &amp; Fixes<br>“Website not found”?</strong><br>Try flushing your DNS cache:<br>Windows: ipconfig /flushdns<br>macOS: sudo dscacheutil -flushcache<br>Linux: sudo systemd-resolve --flush-caches</p><p>Also, try checking with nslookup to see if the DNS server is reachable.</p><h3>🏁 Wrapping Up</h3><p>DNS might operate in the background, but it’s the backbone of how we access the internet. Without it, we’d be stuck typing in confusing IP addresses every time we want to visit a website. From directing traffic to enabling secure email, DNS does more than we realize.</p><p>Now that you’ve peeked under the hood, the next time a site loads, you’ll know the digital dance that made it possible!</p><p>Want a fun twist? 🎉 You can also learn this through an interactive comic at <a href="https://howdns.works/">https://howdns.works</a>. Hope you learn something new from this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bbacdbbc867" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a REST API with Golang using Gorm and Gin]]></title>
            <link>https://medium.com/@tummalayashasree/creating-a-rest-api-with-golang-using-gorm-and-gin-a8cfe57cf80e?source=rss-1c90556dc21c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8cfe57cf80e</guid>
            <dc:creator><![CDATA[Yashasree Tummala]]></dc:creator>
            <pubDate>Sun, 14 May 2023 17:17:59 GMT</pubDate>
            <atom:updated>2023-05-14T17:17:59.722Z</atom:updated>
            <content:encoded><![CDATA[<p>REST APIs are a popular way to build web applications and enable different systems to communicate with each other. Go is a fast and efficient programming language that is becoming increasingly popular for building REST APIs. In this blog post, we’ll walk through the process of creating basic CRUD APIs using Go and GORM. By the end of this post, you will have a basic understanding of how to use these powerful tools to create robust and scalable REST APIs. We’ll cover everything from setting up the environment and provide helpful code examples along the way. So, whether you’re a seasoned Go developer or just getting started, read on to learn how to create REST APIs with Go and GORM!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*4v6PmRxQ5iHM0j8P8ghfYw.png" /></figure><h3>Background</h3><p>Go, also known as Golang, is a fast and efficient programming language developed by Google. It was designed to be simple, scalable, and easy to learn, making it a popular choice for building high-performance web applications. Go’s syntax is concise and expressive, which makes it easy to write and read code.</p><p>GORM is an ORM (Object-Relational Mapping) library for Go that provides a simple and powerful way to interact with databases. It supports a wide range of database engines, including MySQL, PostgreSQL, SQLite, and Microsoft SQL Server. GORM provides a simple and intuitive API that allows developers to interact with their database without having to write SQL code.</p><p>Together, Go and GORM make a great combination for building REST APIs. Go’s performance and efficiency make it well-suited for handling large amounts of traffic, while GORM’s easy-to-use API simplifies database interactions. Additionally, Go’s built-in concurrency support and GORM’s ability to handle database connections in a thread-safe way make them a great choice for building scalable APIs. By using Go and GORM, developers can focus on writing clean and maintainable code, rather than worrying about low-level details.</p><h3>Environment Setup</h3><p>Before we can start building our REST API with Go, GORM, and Gin, we need to set up our development environment. In this section, I’’ll walk through the tools and libraries we’ll be using and how to install and configure them.</p><ol><li><strong>Go</strong>: The first thing we’ll need is Go itself. You can download the latest version of Go from the official website:<a href="https://golang.org/dl/"> https://golang.org/dl/</a>. Follow the installation instructions for your operating system.</li><li><strong>GORM</strong>: Next, we’ll need to install the GORM library. To do this, open a terminal and run the following command: `go get -u gorm.io/gorm` This will install the latest version of GORM and its dependencies.</li><li><strong>Gin</strong>: We’ll be using the Gin web framework to handle HTTP requests and routing. To install Gin, run the following command: go get -u github.com/gin-gonic/gin</li><li><strong>PostgreSQL</strong> driver for GORM: Finally, we need to install the PostgreSQL driver for GORM. To do this, run the following command: go get -u gorm.io/driver/postgres</li></ol><p>With these tools and libraries installed, we’re ready to start building our REST API with Go, GORM, and Gin.</p><h3>Project structure</h3><p>I would like to start with the directory structure before jumping into creation of APIs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*CDaPGSQEEc9qLJasE2DLEA.png" /></figure><ol><li>The db/connection directory contains the code for setting up and managing our database connection. We’ll create a connection.go file in this directory to handle this.</li><li>The end_points directory contains the code for our API endpoints, including functions for creating, reading, updating, and deleting todos. We’ll create separate directories inside end_points for controller, service and repository and have .go files in these directories for each endpoint.</li><li>The model directory contains the code for our data models. We’ll create a todo.go file in this directory to define our Todo model.</li><li>The server directory contains the main entry point for our application. We’ll create a main.go file in this directory to start our server and handle routing.</li></ol><p>This directory structure separates our code into logical sections, making it easier to manage and maintain our application.</p><h3>Setting up the database</h3><pre>&gt;connection.go<br>package connection<br><br>import (<br> &quot;gorm.io/driver/postgres&quot;<br> &quot;gorm.io/gorm&quot;<br>)<br><br>var GormDB *gorm.DB<br><br>func ConnectDatabase() {<br> dsn := &quot;host=localhost user=todo password=postgres dbname=todo port=5432 sslmode=disable TimeZone=Asia/Shanghai&quot;<br> database, err := gorm.Open(postgres.Open(dsn), &amp;gorm.Config{})<br> if err != nil {<br>  panic(&quot;Failed to connect to database!&quot;)<br> }<br> GormDB = database<br>}</pre><p>Here `ConnectDatabase` sets up and manages our database connection. This function uses the PostgreSQL driver to connect to a PostgreSQL database, and stores the resulting *gorm.DB object in the GormDB variable.</p><p>If an error occurs during the database connection process, the function panics with an error message.</p><h3><strong>Entry Point</strong></h3><pre>&gt;main.go<br>package main<br><br>import &quot;migrate/server&quot;<br><br>func main() {<br> server.Run()<br>}</pre><p>This main.go is the entry point of our application. It imports the server package and calls the Run() function from the server package, which sets up the database connection and starts the server.</p><h3><strong>Setting up the Server</strong></h3><pre>&gt;server.go<br>package server<br><br>import (<br> con &quot;migrate/db/connection&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func Run() {<br> con.ConnectDatabase()<br> router := SetUpRouter()<br> router.Run(&quot;localhost:8080&quot;)<br>}<br><br>func SetUpRouter() *gin.Engine {<br> router := gin.New()<br> return router<br>}</pre><p>This Run function calls ConnectDatabase() from the con package to set up the database connection, then calls SetUpRouter() to set up the Gin router and its handlers. Finally, it starts the server on localhost:8080.</p><h3>Creating a Model</h3><pre>&gt;model.go<br>package model<br><br>type Todo struct {<br> Id    int     `json:&quot;id&quot;`<br> Description  string  `json:&quot;description&quot;`<br> Category string `json:category`<br> Priority int `json:priority`<br>}</pre><p>This file provides a simple model for representing todo items in your application. It defines a struct type called Todo.</p><p>The json annotations are used to specify the names of the fields in the JSON representation of the Todo struct.</p><h3>End Points</h3><blockquote>Creating a Controller</blockquote><pre>package controller<br><br>import (<br> &quot;fmt&quot;<br> &quot;migrate/endpoint/service&quot;<br> &quot;migrate/model&quot;<br> &quot;net/http&quot;<br> &quot;strconv&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>type TodoController struct {<br> todoService service.TodoService<br>}<br><br>func NewTodoController(todoService service.TodoService) *TodoController {<br> return &amp;TodoController{<br>  todoService: todoService,<br> }<br>}<br><br>func (tc *TodoController) MakeAddTodo(c *gin.Context) {<br> var todo model.Todo<br><br> if err := c.ShouldBindJSON(&amp;todo); err != nil {<br>  fmt.Print(err)<br>  c.AbortWithStatusJSON(http.StatusBadRequest, err)<br>  return<br> }<br><br> addedTodo, err := tc.todoService.Add(&amp;todo)<br> fmt.Print(addedTodo)<br> if err != nil {<br>  c.AbortWithStatusJSON(http.StatusBadRequest, err.Error())<br> } else {<br>  c.IndentedJSON(http.StatusCreated, addedTodo)<br> }<br>}<br><br>func (tc *TodoController) MakeGetTodo(c *gin.Context) {<br> reqid := c.Param(&quot;id&quot;)<br> id, _ := strconv.Atoi(reqid)<br><br> todo, err := tc.todoService.GetTodo(id)<br> if err != nil {<br>  c.AbortWithStatusJSON(http.StatusBadRequest, err.Error())<br> } else {<br>  c.IndentedJSON(http.StatusCreated, todo)<br> }<br><br>}<br><br>func (tc *TodoController) MakeGetAllTodo(c *gin.Context) {<br><br> todo, err := tc.todoService.GetAllTodo()<br> if err != nil {<br>  c.AbortWithStatusJSON(http.StatusBadRequest, err.Error())<br> } else {<br>  c.IndentedJSON(http.StatusCreated, todo)<br> }<br>}</pre><p>This code defines a controller for handling HTTP requests related to the Todo model for adding, retrieving, and retrieving all Todo items.</p><p>The TodoController struct has a single field todoService, which is an instance of the TodoService</p><p>The NewTodoController function creates a new instance of TodoController with the given TodoService.</p><p>The MakeAddTodo function is a handler function for adding a new Todo item. It reads the JSON data from the request body, parses it into a Todo struct, and calls the Add method of the todoService to add the new Todo item. If successful, it returns a JSON response with the newly created Todo item and an HTTP status code of 201 Created. If an error occurs, it returns an HTTP status code of 400 Bad Request with the error message. Similarly for the Get and GetAll as well.</p><blockquote>Creating a Service</blockquote><pre>package service<br><br>import (<br> &quot;migrate/endpoint/repository&quot;<br> &quot;migrate/model&quot;<br>)<br><br>type TodoService interface {<br> Add(*model.Todo) (*model.Todo, error)<br> GetTodo(int) (*model.Todo, error)<br> GetAllTodo() ([]model.Todo, error)<br>}<br><br>type todoService struct {<br> todoRepo repository.TodoRepository<br>}<br><br>func NewTodoService(todoRepository repository.TodoRepository) *todoService {<br> return &amp;todoService{<br>  todoRepo: todoRepository,<br> }<br>}<br>func (b *todoService) Add(todo *model.Todo) (*model.Todo, error) {<br> err := b.todoRepo.Create(todo)<br><br> if err != nil {<br>  return nil, err<br> }<br> return todo, nil<br>}<br><br>func (b *todoService) GetTodo(id int) (*model.Todo, error) {<br> todo, err := b.todoRepo.GetTodoById(id)<br><br> if err != nil {<br>  return nil, err<br> }<br> return todo, nil<br>}<br><br>func (b *todoService) GetAllTodo() ([]model.Todo, error) {<br> todo, err := b.todoRepo.GetAllTodos()<br><br> if err != nil {<br>  return nil, err<br> }<br> return todo, nil<br>}</pre><p>This interface defines three methods: Add, GetTodo, and GetAllTodo, and the implementation defines these methods by using a TodoRepository to interact with a database.</p><p>The NewTodoService function creates a new instance of todoService by accepting a TodoRepository as an argument and returning a pointer to the new instance.</p><p>The Add method takes a pointer to a model. Todo as an argument, calls the Create method of the TodoRepository to save the new Todo, and returns the saved Todo along with any error that occurred during the operation.</p><p>The GetTodo method takes an integer ID as an argument, calls the GetTodoById method of the TodoRepository to fetch the Todo with the given ID, and returns the Todo along with any error that occurred during the operation.</p><p>The GetAllTodo method calls the GetAllTodos method of the TodoRepository to fetch all Todos and returns them along with any error that occurred during the operation.</p><blockquote>Creating a Repository</blockquote><pre>package repository<br><br>import (<br> &quot;migrate/model&quot;<br><br> &quot;gorm.io/gorm&quot;<br>)<br><br>type TodoRepository interface {<br> Create(*model.Todo) error<br> GetTodoById(int) (*model.Todo, error)<br> GetAllTodos() ([]model.Todo, error)<br>}<br><br>type todoRepository struct {<br> db *gorm.DB<br>}<br><br>func NewTodoRepository(db *gorm.DB) *todoRepository {<br> return &amp;todoRepository{<br>  db: db,<br> }<br>}<br>func (repo *todoRepository) Create(product *model.Todo) error {<br> db := repo.db.Create(product)<br> if db.Error != nil {<br>  return db.Error<br> }<br> return nil<br>}<br><br>func (repo *todoRepository) GetTodoById(id int) (*model.Todo, error) {<br> var todo model.Todo<br><br> db := repo.db.Model(&amp;model.Todo{}).Where(&quot;id=?&quot;, id).First(&amp;todo)<br><br> if db.Error != nil {<br>  return &amp;model.Todo{}, db.Error<br> }<br> return &amp;todo, nil<br>}<br><br>func (repo *todoRepository) GetAllTodos() ([]model.Todo, error) {<br> var todo []model.Todo<br><br> db := repo.db.Find(&amp;todo)<br><br> if db.Error != nil {<br>  return nil, db.Error<br> }<br> return todo, nil<br><br>}</pre><p>The NewTodoRepository function creates a new instance of the todoRepository struct by taking a gorm.DB as input. The todoRepository struct contains a single field, db, which is a reference to the gorm.DB instance.</p><p>The Create method takes a *model.Todo pointer as input, creates a new todo item in the database using the db.Create() function and returns an error if one occurred.</p><p>The GetTodoById method takes an int ID as input, retrieves the corresponding todo item from the database using the db.Model() and db.First() functions, and returns the todo item and an error if one occurred.</p><p>The GetAllTodos method retrieves all the todo items from the database using the db.Find() function and returns the todo items and an error if one occurred.</p><h3>Update the server.go</h3><pre>package server<br>import (<br> &quot;migrate/endpoint/controller&quot;<br> &quot;migrate/endpoint/repository&quot;<br> &quot;migrate/endpoint/service&quot;<br> con &quot;migrate/db/connection&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func Run() {<br> con.ConnectDatabase()<br> router := SetUpRouter()<br> router.Run(&quot;localhost:8080&quot;)<br>}<br><br>func setUp() controller.TodoController {<br> todoRepo := repository.NewTodoRepository(con.GormDB)<br> todoService := service.NewTodoService(todoRepo)<br> todoController := controller.NewTodoController(todoService)<br><br> return *todoController<br>}<br><br>func SetUpRouter() *gin.Engine {<br> router := gin.New()<br> handler := setUp()<br><br> router.POST(&quot;/todos&quot;, handler.MakeAddTodo)<br> router.GET(&quot;/todos/:id&quot;, handler.MakeGetTodo)<br> router.GET(&quot;/todos&quot;, handler.MakeGetAllTodo)<br> return router<br>}</pre><p>Now that we have all end points in place -</p><p>The Run() function first connects to a database, and then sets up the router using the SetUpRouter() function. The router is then started using the Run() method, listening on localhost:8080.</p><p>The SetUpRouter() function initializes a new Gin router, and then calls the setUp() function to get a reference to the TodoController. It then maps HTTP routes to the controller&#39;s methods, using the MakeAddTodo(), MakeGetTodo(), and MakeGetAllTodo() methods to handle HTTP requests.</p><p>The setUp() function initializes the TodoRepository using NewTodoRepository() and passes the GormDB database connection from con package. It then initializes the TodoService using NewTodoService() and passing the TodoRepository as an argument. Finally, it initializes the TodoController using NewTodoController() and passing the TodoService as an argument.</p><p>As an end note this code sets up a web server using the Gin framework, initializes a TodoController and maps HTTP routes to its methods. The TodoController relies on a TodoService, which in turn relies on a TodoRepository to perform CRUD operations on a database.</p><h3>Summary</h3><p>After building this project, you should now have a good grasp of how to use Gin and Gorm to create a RESTful API, implement CRUD functionality, and understand how these two frameworks interact with each other. However, there are many ways to further enhance this application, such as implementing unit testing, containerization with Docker, and other advanced techniques that you can explore to deepen your understanding.</p><p>To learn more about GORM &amp; Gin, you can refer to the official documentation available at <a href="https://gorm.io/docs/">https://gorm.io/docs/</a> &amp; <a href="https://gin-gonic.com/docs/">https://gin-gonic.com/docs/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8cfe57cf80e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>