<?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 Nidhi D on Medium]]></title>
        <description><![CDATA[Stories by Nidhi D on Medium]]></description>
        <link>https://medium.com/@cp-nidhi-d?source=rss-2a334125442f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JF9MtGSTpdMAHT5YKPDACA.jpeg</url>
            <title>Stories by Nidhi D on Medium</title>
            <link>https://medium.com/@cp-nidhi-d?source=rss-2a334125442f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:49:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cp-nidhi-d/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[Golang: Struct, Interface And Dependency Injection(DI)]]></title>
            <link>https://medium.com/canopas/golang-struct-interface-and-dependency-injection-di-08f8ffddf87d?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/08f8ffddf87d</guid>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[dependencies]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[interfaces]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 07:11:38 GMT</pubDate>
            <atom:updated>2025-01-17T07:11:38.366Z</atom:updated>
            <content:encoded><![CDATA[<h4>Write Clean, Flexible, and Testable Go Code with Structs and Interfaces!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rFpOgaYKSgTupAazOIcvg.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">home</a>! 🚀</blockquote><h3>Background</h3><p>In this blog, we will explore when to use structs versus interfaces in Go and how to leverage both for Dependency Injection (DI).</p><p>To make these concepts easier to grasp, we’ll use a simple analogy of a <strong>Toy Box.</strong></p><h3>Understanding with a real-world example: Toy Box</h3><h4><strong>Structs</strong></h4><ul><li>Think of a struct as a specific toy in a toy box, like a car.</li><li>The car has specific features, like its color, size, and type (e.g., sports car).</li><li>In programming, a struct holds data about an object.</li></ul><h4><strong>Interfaces</strong></h4><ul><li>An interface is like a toy box that can hold any type of toy.</li><li>It defines what toys can do, like roll, make noise, or light up. Any toy that can perform these actions can fit in the toy box.</li><li>In programming, an interface defines a set of methods that different types(struct) can implement.</li></ul><h4>Dependency Injection</h4><ul><li>Imagine a child who plays with toys. Instead of the child only being able to play with one specific toy, you let them choose any toy from the toy box whenever they want.</li><li>This is like dependency injection, where you provide a function or class with the tools (or dependencies) it needs to work, allowing for flexibility.</li></ul><h3>Understanding the Basics</h3><h4><strong>Structs</strong></h4><ul><li><strong>Definition:</strong> A struct is a way to define a new type with specific fields.</li><li><strong>Purpose:</strong> Useful for modeling data structures and encapsulating data and behavior within a single unit.</li></ul><p>Example,</p><pre>type Car struct {<br>    Model string<br>    Year  int<br>}</pre><h4><strong>Interfaces</strong></h4><ul><li><strong>Definition:</strong> An interface defines a set of methods that a type must implement.</li><li><strong>Purpose:</strong> Crucial for polymorphism and decoupling components, enabling generic programming.</li></ul><p>Example,</p><pre>type CarInterface interface {<br>    Start()<br>    Stop()<br>}</pre><p>Implement CarInterface using Car struct,</p><pre>func (c *Car) Start() {<br>    fmt.Println(&quot;Car started&quot;)<br>}<br><br>func (c *Car) Stop() {<br>    fmt.Println(&quot;Car stopped&quot;)<br>}</pre><h3>When to Use Which?</h3><h4><strong>Use Structs When,</strong></h4><ul><li>You need to model a specific data structure with defined fields.</li><li>You want to encapsulate data and behavior within a single unit.</li></ul><h4><strong>Use Interfaces When,</strong></h4><ul><li>You want to define a contract that multiple types can implement.</li><li>You need to decouple components and make your code more flexible and testable.</li><li>You want to leverage polymorphism to write generic code.</li></ul><h3>Balancing Flexibility and Performance</h3><p>While interfaces provide flexibility, dynamic method calls can introduce overhead.</p><p>Structs, on the other hand, offer performance advantages due to static type checking and direct method calls. Below are the ways to strike the balance:</p><h4><strong>Interface Composition</strong></h4><p>Combine multiple interfaces to create more specific interfaces. For example, consider a file system interface:</p><pre>type Reader interface {<br>    Read(p []byte) (n int, err error)<br>}<br><br>type Writer interface {<br>    Write(p []byte) (n int, err error)<br>}</pre><p>Now, we can create a more specific interface ReadWrite, by composing Reader and Writer:</p><pre>type ReadWrite interface {<br>    Reader<br>    Writer<br>}</pre><p><strong>Benefit:</strong> This approach promotes modularity, reusability, and flexibility in your code.</p><h4><strong>Interface Embedding</strong></h4><p>Embed interfaces within structs to inherit their methods. For example, consider a logging interface:</p><pre>type Logger interface {<br>    Log(message string)<br>}</pre><p>Now, we can create a more specific interface, ErrorLogger, which embeds the Logger interface:</p><pre>type ErrorLogger interface {<br>    Logger<br>    LogError(err error)<br>}</pre><p>Any type that implements the ErrorLogger interface must also implement the Log method inherited from the embedded Logger interface.</p><pre>type ConsoleLogger struct{}<br><br>func (cl *ConsoleLogger) Log(message string) {<br>    fmt.Println(message)<br>}<br><br>func (cl *ConsoleLogger) LogError(err error) {<br>    fmt.Println(&quot;Error:&quot;, err)<br>}</pre><p><strong>Benefit:</strong> This can be used to create hierarchical relationships between interfaces, making your code more concise and expressive.</p><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/golang-struct-interface-and-dependency-injection"><strong><em>this blog</em></strong></a><strong><em>.</em></strong></blockquote><h3>Similar Articles</h3><ul><li><a href="https://medium.com/canopas/how-to-use-enums-in-golang-ff682b927f0d">How to use Enums in Golang</a></li><li><a href="https://medium.com/canopas/function-types-and-higher-order-functions-in-go-8ea2e95d1860">Function Types and Higher-Order Functions in Go</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08f8ffddf87d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/golang-struct-interface-and-dependency-injection-di-08f8ffddf87d">Golang: Struct, Interface And Dependency Injection(DI)</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang + htmx + Tailwind CSS: Create a Responsive Web Application]]></title>
            <link>https://medium.com/canopas/golang-htmx-tailwind-css-create-a-responsive-web-application-4771540685f3?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4771540685f3</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[ssrs]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 14:07:42 GMT</pubDate>
            <atom:updated>2024-11-19T12:44:27.347Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to implementing web app without using Javascript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwQbCnRbWq9A_EzLPNEBZw.png" /><figcaption>Designed By <a href="https://canopas.com/">canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">home</a>! 🚀</blockquote><h3>Background</h3><p>In today’s web development landscape, JavaScript has long been the language of choice for creating dynamic and interactive web applications.</p><blockquote>As a Go developer, what if you don’t want to use Javascript and still implement a responsive web application?</blockquote><p>Imagine a sleek to-do list app that updates instantly as you check off tasks without a full-page reload. This is the power of Golang and htmx!</p><p>Combining Go and htmx allows us to create responsive and interactive web applications without writing a single line of JavaScript.</p><p>In this blog, we will explore how to use htmx and Golang to build web applications. (It can be used with other your favorite platforms, too.)</p><p>As a learning, we will implement basic create and delete operations for users.</p><p>This blog is also available as a Youtube video, feel free to check it out.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FI38mkAvzOJA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DI38mkAvzOJA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FI38mkAvzOJA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5d06e1838ec29292ce74343bdb56345/href">https://medium.com/media/b5d06e1838ec29292ce74343bdb56345/href</a></iframe><h3><strong>What is </strong>htmx<strong>?</strong></h3><p><a href="https://htmx.org/">htmx</a> is a modern HTML extension that adds bidirectional communication between the browser and the server.</p><p>It allows us to create dynamic web pages without writing JavaScript, as it provides access to AJAX, server-sent events, etc in HTML directly.</p><h3>How htmx works?</h3><ul><li>When a user interacts with an element that has an htmx attribute (e.g., clicks a button), the browser triggers the specified event.</li><li>htmx intercepts the event and sends an HTTP request to the server-side endpoint specified in the attribute (e.g., hx-get=&quot;/my-endpoint&quot;).</li><li>The server-side endpoint processes the request and generates an HTML response.</li><li>htmx receives the response and updates the DOM according to the hx-target and hx-swap attributes. This can involve:</li></ul><blockquote>— Replacing the entire element’s content.<br> — Inserting new content before or after the element.<br> — Appending content to the end of the element.</blockquote><p>Let’s understand it in more depth with an example.</p><pre>&lt;button hx-get=&quot;/fetch-data&quot; hx-target=&quot;#data-container&quot;&gt;<br>   Fetch Data<br>&lt;/button&gt;<br>&lt;div id=&quot;data-container&quot;&gt;&lt;/div&gt;</pre><p>In the above code, when the button is clicked:</p><ol><li>htmx sends a GET request to /fetch-data.</li><li>The server-side endpoint fetches data and renders it as HTML.</li><li>The response is inserted into the #data-container element.</li></ol><h3>Create and delete the user</h3><p>Below are the required tools/frameworks to build this basic app.</p><ul><li>Gin (Go framework)</li><li>Tailwind CSS</li><li>htmx</li></ul><h4>Basic setup</h4><ul><li>Create main.go file at the root directory.</li></ul><p><strong>main.go</strong></p><pre><br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func main() {<br> router := gin.Default()<br><br> router.Run(&quot;:8080&quot;)<br> fmt.Println(&quot;Server is running on port 8080&quot;)<br>}</pre><blockquote>It sets up a basic Go server, running at port <strong>8080. <br></strong>Run go run main.go to run the application.</blockquote><ul><li>Create a HTML file at the root directory, to render the user list.</li></ul><p><strong>users.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>   &lt;head&gt;<br>      &lt;title&gt;Go + htmx app &lt;/title&gt;<br>      &lt;script src=&quot;https://unpkg.com/htmx.org@2.0.0&quot; integrity=&quot;sha384-wS5l5IKJBvK6sPTKa2WZ1js3d947pvWXbPJ1OmWfEuxLgeHcEbjUUA5i9V5ZkpCw&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>      &lt;script src=&quot;https://cdn.tailwindcss.com&quot;&gt;&lt;/script&gt;<br>   &lt;/head&gt;<br>   &lt;body class=&quot;text-center flex flex-col w-full gap-6 mt-10&quot;&gt;<br>      &lt;table id=&quot;user-list&quot; class=&quot;w-1/2 mx-auto mt-4 border border-gray-300&quot;&gt;<br>         &lt;thead&gt;<br>            &lt;tr class=&quot;border border-gray-300&quot;&gt;<br>               &lt;th class=&quot;px-4 py-2&quot;&gt;Name&lt;/th&gt;<br>               &lt;th class=&quot;px-4 py-2&quot;&gt;Email&lt;/th&gt;<br>               &lt;th class=&quot;px-4 py-2&quot;&gt;Actions&lt;/th&gt;<br>            &lt;/tr&gt;<br>         &lt;/thead&gt;<br>         &lt;tbody&gt;<br>            {{ range .users }}<br>            &lt;tr class=&quot;border border-gray-300&quot;&gt;<br>               &lt;td class=&quot;px-4 py-2&quot;&gt;{{ .Name }}&lt;/td&gt;<br>               &lt;td class=&quot;px-4 py-2&quot;&gt;{{ .Email }}&lt;/td&gt;<br>               &lt;td class=&quot;px-4 py-2&quot;&gt;<br>                  &lt;button class=&quot;bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded&quot;&gt;Delete&lt;/button&gt;<br>               &lt;/td&gt;<br>            &lt;/tr&gt;<br>            {{ end }}<br>         &lt;/tbody&gt;<br>      &lt;/table&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><blockquote>We have included,<br>- <strong>htmx</strong> using the script tag — <a href="https://unpkg.com/htmx.org@2.0.0">https://unpkg.com/htmx.org@2.0.0</a><br>- <strong>Tailwind CSS </strong>with cdn link — <a href="https://cdn.tailwindcss.com/">https://cdn.tailwindcss.com</a></blockquote><p>Now, we can use Tailwind CSS classes and render the templates with htmx.</p><p>As we see in users.html, we need to pass <strong>users</strong> array to the template, so that it can render the users list.</p><p>For that let’s create a hardcoded static list of users and create a route to render users.html .</p><h4>Fetch users</h4><p><strong>main.go</strong></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;text/template&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func main() {<br> router := gin.Default()<br><br> router.GET(&quot;/&quot;, func(c *gin.Context) {<br>  users := GetUsers()<br><br>  tmpl := template.Must(template.ParseFiles(&quot;users.html&quot;))<br>  err := tmpl.Execute(c.Writer, gin.H{&quot;users&quot;: users})<br>    if err != nil {<br>       panic(err)<br>    }<br> })<br><br> router.Run(&quot;:8080&quot;)<br> fmt.Println(&quot;Server is running on port 8080&quot;)<br>}<br><br>type User struct {<br> Name  string<br> Email string<br>}<br><br>func GetUsers() []User {<br> return []User{<br>  {Name: &quot;John Doe&quot;, Email: &quot;johndoe@example.com&quot;},<br>  {Name: &quot;Alice Smith&quot;, Email: &quot;alicesmith@example.com&quot;},<br> }<br>}</pre><blockquote>We have added a route / to render the user list and provide a static list of users (to which we will add new users ahead).</blockquote><p>That’s all. Restart the server and let’s visit — <a href="http://localhost:8080/"><strong>http://localhost:8080/</strong></a><strong> </strong>to check whether it renders the user list or not. It will render the user list as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXKnAX4UhHuE1xX5KGkJYA.png" /><figcaption>Rendered users list</figcaption></figure><h4>Create user</h4><ul><li>Create file <strong>user_row.html</strong>. It will be responsible for adding a new user row to the user table.</li></ul><p><strong>user_row.html</strong></p><pre>&lt;tr class=&quot;border border-gray-300&quot;&gt;<br>    &lt;td class=&quot;px-4 py-2&quot;&gt;{{ .Name }}&lt;/td&gt;<br>    &lt;td class=&quot;px-4 py-2&quot;&gt;{{ .Email }}&lt;/td&gt;<br>    &lt;td class=&quot;px-4 py-2&quot;&gt;<br>        &lt;button class=&quot;bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded&quot;&gt;Delete&lt;/button&gt;<br>    &lt;/td&gt;<br>&lt;/tr&gt;</pre><p>P.S. — You will notice that it has the same structure as the user table row in users.html . That’s because we want the same styling for the new row we are going to add.</p><ul><li>Modify <strong>users.html</strong>. Add the Below code above the &lt;table&gt;&lt;/table&gt; tags.</li></ul><pre>&lt;form hx-post=&quot;/users&quot; hx-target=&quot;#user-list&quot; hx-swap=&quot;beforeend&quot;&gt;<br>   &lt;input type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;Name&quot; class=&quot;border border-gray-300 p-2 rounded&quot;&gt;<br>   &lt;input type=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;Email&quot; class=&quot;border border-gray-300 p-2 rounded&quot;&gt;<br>   &lt;button type=&quot;submit&quot; class=&quot;bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded&quot;&gt;Add User&lt;/button&gt;<br>&lt;/form&gt;</pre><blockquote><strong>hx-post=“/users”</strong> — When the form will be submitted, it will trigger post request to /users route.</blockquote><blockquote><strong>hx-target=“#user-list” —</strong>Specify the target where we want to add data.</blockquote><blockquote><strong>hx-swap=“beforeend” — </strong>Specify the position where want to add data. In our case we want to add new user at the end of list, so we have used beforeend value.</blockquote><ul><li>Let’s implement /users(POST) route in<strong> </strong>the<strong> main.go</strong> file.</li></ul><pre>router.POST(&quot;/users&quot;, func(c *gin.Context) {<br>  tmpl := template.Must(template.ParseFiles(&quot;user_row.html&quot;))<br><br>  name := c.PostForm(&quot;name&quot;)<br>  email := c.PostForm(&quot;email&quot;)<br><br>  user := User{Name: name, Email: email}<br>  err := tmpl.Execute(c.Writer, user)<br>  if err != nil {<br>   panic(err)<br>  }<br>})</pre><blockquote>It takes the <strong>name</strong> and <strong>email</strong> from the form input and executes the <strong>user_row.html</strong>.</blockquote><p>Let’s try to add a new user to the table. Visit <a href="http://localhost:8080/"><strong>http://localhost:8080/</strong></a><strong> </strong>and click the <strong>Add Use</strong>r button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJqXzPGhcdC2gnJtotfeNw.gif" /><figcaption>Add new user to the list</figcaption></figure><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/golang-htmx-tailwind-css-create-responsive-web-application"><strong><em>this blog</em></strong></a><strong><em>.</em></strong></blockquote><h3>Similar Articles</h3><ul><li><a href="https://medium.com/canopas/how-to-use-enums-in-golang-ff682b927f0d">How to use Enums in Golang</a></li><li><a href="https://medium.com/canopas/function-types-and-higher-order-functions-in-go-8ea2e95d1860">Function Types and Higher-Order Functions in Go</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4771540685f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/golang-htmx-tailwind-css-create-a-responsive-web-application-4771540685f3">Golang + htmx + Tailwind CSS: Create a Responsive Web Application</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write E2E tests for Next.js Application using Playwright]]></title>
            <link>https://medium.com/canopas/how-to-write-e2e-tests-for-next-js-application-using-playwright-1c76bb011426?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c76bb011426</guid>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[playwright-automation]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 06:39:47 GMT</pubDate>
            <atom:updated>2024-11-19T12:47:24.348Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To Write E2E Tests for Next.js Application Using Playwright</h3><h4>A detailed guide for using Playwright as your automated testing tool</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlXFd1aMOqyvEmmP-Ec9aw.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">home</a>! 🚀</blockquote><h3>Background</h3><p>Imagine building a house without carefully reviewing the blueprints or measuring the materials.</p><p>You might have misaligned walls, incorrectly sized windows, or structural issues. Similarly, while developing an application, neglecting tests can lead to:</p><ul><li><strong>Unexpected errors:</strong> Bugs and errors can go unnoticed until users face your application, potentially causing significant problems to users. Of course, That you will never want!</li><li><strong>Poor user experience:</strong> A buggy application can frustrate users and damage your reputation.</li><li><strong>Increased maintenance costs:</strong> Fixing bugs after they’ve been discovered can be time-consuming and expensive.</li></ul><p>By investing time in testing your code, you’re essentially building a solid foundation for your application, ensuring its reliability, quality, and maintainability.</p><h3>Why E2E tests?</h3><p>E2E tests validate that the entire user journey functions correctly, from login to checkout or any other complex process. They ensure that the application provides a seamless and intuitive user experience.</p><p>We can easily detect any broken link, invalid user input, or any UI/UX problem that is laughing in the corner!</p><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><p>You might say, the tests take up much of my time 😨. Trust me, it will be worth it!!</p><p>Multiple tools are available for testing, such as Jest, Cypress, Playwright, etc. Each has advantages and drawbacks.</p><p>As we are going to perform End-to-End tests, Playwright is the testing tool that has more advantages over any other tools, specifically Cypress.</p><p>Hence, we will go with the <a href="https://playwright.dev/"><strong>playwright</strong></a> in this blog.</p><p>Without further ado, let’s go ahead!!</p><p>This blog is also available as a YouTube video, feel free to check it out.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAuHg6bsrP_A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAuHg6bsrP_A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAuHg6bsrP_A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c072cbd91e20c18396e975373e91e6d/href">https://medium.com/media/7c072cbd91e20c18396e975373e91e6d/href</a></iframe><h3>Prerequisites</h3><p>Consider installing Node.js as a first step, if you don’t have one already.</p><p>Before we start, let’s first create a Next.js application. We will use it throughout the blog.</p><p>Execute the below command to create the Next.js app.</p><pre>npx create-next-app@latest</pre><p>It will ask questions for configuring the app, respond to them, and we’re ready with the app.</p><h3>Setup steps</h3><h4>Installation</h4><ul><li>Execute the command to install the playwright.</li></ul><pre>npm init playwright@latest</pre><ul><li>It will ask you certain questions for configuring the playwright tool in your project.</li></ul><h4>Configuration</h4><ul><li>After completing the configuration, you will find some of the files created inside the project folder, but we will only need the <strong>playwright.config.ts </strong>file and the <strong>tests </strong>directory from them.</li></ul><p><strong>playwright.config.ts</strong></p><pre>import { defineConfig, devices } from &#39;@playwright/test&#39;;<br><br>/**<br> * Read environment variables from file.<br> * https://github.com/motdotla/dotenv<br> */<br>// import dotenv from &#39;dotenv&#39;;<br>// import path from &#39;path&#39;;<br>// dotenv.config({ path: path.resolve(__dirname, &#39;.env&#39;) });<br><br>/**<br> * See https://playwright.dev/docs/test-configuration.<br> */<br>export default defineConfig({<br>  testDir: &#39;./tests&#39;,<br>  /* Run tests in files in parallel */<br>  fullyParallel: true,<br>  /* Fail the build on CI if you accidentally left test.only in the source code. */<br>  forbidOnly: !!process.env.CI,<br>  /* Retry on CI only */<br>  retries: process.env.CI ? 2 : 0,<br>  /* Opt out of parallel tests on CI. */<br>  workers: process.env.CI ? 1 : undefined,<br>  /* Reporter to use. See https://playwright.dev/docs/test-reporters */<br>  reporter: &#39;html&#39;,<br>  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */<br>  use: {<br>    /* Base URL to use in actions like `await page.goto(&#39;/&#39;)`. */<br>    // baseURL: &#39;http://127.0.0.1:3000&#39;,<br><br>    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */<br>    trace: &#39;on-first-retry&#39;,<br>  },<br><br>  /* Configure projects for major browsers */<br>  projects: [<br>    {<br>      name: &#39;chromium&#39;,<br>      use: { ...devices[&#39;Desktop Chrome&#39;] },<br>    },<br><br>    {<br>      name: &#39;firefox&#39;,<br>      use: { ...devices[&#39;Desktop Firefox&#39;] },<br>    },<br><br>    // {<br>    //   name: &#39;webkit&#39;,<br>    //   use: { ...devices[&#39;Desktop Safari&#39;] },<br>    // },<br><br>    /* Test against mobile viewports. */<br>    // {<br>    //   name: &#39;Mobile Chrome&#39;,<br>    //   use: { ...devices[&#39;Pixel 5&#39;] },<br>    // },<br>    // {<br>    //   name: &#39;Mobile Safari&#39;,<br>    //   use: { ...devices[&#39;iPhone 12&#39;] },<br>    // },<br><br>    /* Test against branded browsers. */<br>    // {<br>    //   name: &#39;Microsoft Edge&#39;,<br>    //   use: { ...devices[&#39;Desktop Edge&#39;], channel: &#39;msedge&#39; },<br>    // },<br>    // {<br>    //   name: &#39;Google Chrome&#39;,<br>    //   use: { ...devices[&#39;Desktop Chrome&#39;], channel: &#39;chrome&#39; },<br>    // },<br>  ],<br><br>  /* Run your local dev server before starting the tests */<br>  // webServer: {<br>  //   command: &#39;npm run start&#39;,<br>  //   url: &#39;http://127.0.0.1:3000&#39;,<br>  //   reuseExistingServer: !process.env.CI,<br>  // },<br>});</pre><blockquote><strong>testDir</strong> — Path where our test files live</blockquote><blockquote><strong>projects — </strong>Defines the browsers, in which we want to run the tests. It will run all the provided tests in all browsers. <br>i.e. total test executions will be <strong>no. of test cases * no. of browsers</strong></blockquote><blockquote><strong>webServer — </strong>This block presents our server url, for lcoal environment it will be <strong>http://127.0.0.1:3000</strong></blockquote><blockquote>modify the webServer block as below, if the <strong>url</strong> doesn’t load local server:<br> <strong>webServer: {<br> command: ‘npm run start’,<br> port: 3000,<br> reuseExistingServer: true,<br>}</strong></blockquote><p>Notes:</p><ul><li>It also provides an option to mention a specific device or a browser on which we want to execute tests. P.S. <strong>/* Test against mobile viewports. */</strong> section.</li><li>Before running the tests, ensure the application is already running on the <strong>url</strong> provided in the<strong> webserver</strong> config. If it is running on a different port, consider updating it accordingly.</li></ul><h3>Implement user login flow</h3><p>To test user login flow, let’s first create it.</p><blockquote>Please note that I have used an App router in Next.js that’s why I added the login page at <strong>/src/app.</strong><br>If you use a Page router then add the <strong>/login/page.tsx</strong> into <strong>/src/pages</strong> directory.</blockquote><p><strong>src/app/login/page.tsx</strong></p><pre>&quot;use client&quot;;<br><br>import { useState } from &#39;react&#39;;<br>import { FormEvent } from &#39;react&#39;<br><br><br>export default function LoginForm() {<br>  const [email, setEmail] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br>  const [errorMessage, setErrorMessage] = useState(&quot;&quot;);<br><br>  const handleLogin = async (e: FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    e.preventDefault();<br><br>    // Validate the form<br>    if (!email || !password) {<br>      setErrorMessage(&#39;Please fill in all fields&#39;);<br>      return;<br>    }<br><br>    // Simulate a login request<br>    if (email === &quot;johndoe@gmail.com&quot; &amp;&amp; password === &quot;pass1234&quot;) {<br>      window.location.href = &quot;/&quot;;<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&#39;flex justify-center items-center h-screen&#39;&gt;<br>      &lt;form onSubmit={handleLogin} className=&#39;flex flex-col gap-3 w-[300px] text-black&#39;&gt;<br>      &lt;input<br>        type=&quot;email&quot;<br>        placeholder=&quot;Email&quot;<br>        value={email}<br>        onChange={(e) =&gt; setEmail(e.target.value)}<br>        className=&#39;p-3&#39;<br>      /&gt;<br>      &lt;input<br>        type=&quot;password&quot;<br>        placeholder=&quot;Password&quot;<br>        value={password}<br>        onChange={(e) =&gt; setPassword(e.target.value)}<br>        className=&#39;p-3&#39;<br>      /&gt;<br>      &lt;button type=&quot;submit&quot; className=&#39;bg-blue-500 p-3 w-fit mx-auto&#39;&gt;Login&lt;/button&gt;<br>      {errorMessage &amp;&amp; &lt;p&gt;{errorMessage}&lt;/p&gt;}<br>    &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this simple component, we’re expecting users to input their email and password to log in to the application.</p><p>For simplicity purposes, I have simulated the login request by just matching the email and password to static values(Don’t take it seriously though😃).</p><p>There are two scenarios,</p><ul><li><strong>If the login succeeds — Redirect the user to the home screen(“/”)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7slh1uogwrfeXjj26S14A.gif" /><figcaption>Successful login</figcaption></figure><ul><li><strong>In case login fails — Stay on the login page and show the error message</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7IlNtNUW7bd05uKKcOFQg.gif" /><figcaption>Login fails</figcaption></figure><p>Let’s test both scenarios now.</p><p><strong>P.S. Make sure the app is running while executing the tests, as we will need to test redirection using a real URL.</strong></p><h3>End-to-End testing</h3><p>As we have configured /tests directory in the <strong>playwright.config.ts</strong>, we asked the playwright to look into this directory and execute tests from there. Consider modifying it, if you want to use some other directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*05jhQG2sucYWSIiGnh8Ghg.png" /><figcaption>Playwright config for tests directory</figcaption></figure><p>Let’s create <strong>login.spec.ts </strong>in the <strong>tests</strong> directory<strong>, </strong>you can name it whatever you want (There’s no convention for it).</p><p>For simplicity purposes, I have named it as the feature name.</p><p>Let’s first collect the steps, we are going to test for successful login.</p><ol><li>Navigate to the login page</li><li>Fill in the email and password fields</li><li>Click on the <strong>Login</strong> button</li><li>Next steps will be executed according to the login success/failure scenario</li></ol><ul><li>For a successful login case — We will verify whether the current page is the home page</li><li>For failure case — We will check the current page is login and the error message is set.</li></ul><p>Let’s write our first test case for <strong>successful</strong> login.</p><pre>test(&#39;Login form successfully redirects on valid credentials&#39;, async ({ page }) =&gt; {<br>  // Navigate to the login page  <br>  await page.goto(&#39;/login&#39;); // Replace with your development URL<br><br>  // Fill in the email and password fields<br>  await page.fill(&#39;input[type=&quot;email&quot;]&#39;, &#39;johndoe@gmail.com&#39;);<br>  await page.fill(&#39;input[type=&quot;password&quot;]&#39;, &#39;pass1234&#39;);<br><br>  // Click the login button<br>  await page.click(&#39;button[type=&quot;submit&quot;]&#39;);<br><br>  // Wait for the page to redirect<br>  await page.waitForURL(&quot;/&quot;);<br><br>  // Assert that the user is redirected to the homepage<br>  await expect(page).toHaveURL(&#39;/&#39;); // Replace with your homepage URL<br>});</pre><p>Here, we have provided the valid credentials and thus the login check passed and redirected to the home page.</p><p>Let’s check by running the test command inside the project directory.</p><pre>npx playwright test</pre><p>Hurray! Our first test is passed successfully🎉🎊.</p><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/how-to-write-E2E-tests-for-nextjs-application-using-playwright"><strong><em>this blog</em></strong></a><strong><em>.</em></strong></blockquote><h3>Similar Articles</h3><ul><li><a href="https://blog.canopas.com/vue-3-component-testing-with-jest-8b80a8a8946b">Vue 3 component testing with Jest</a></li><li><a href="https://blog.canopas.com/vue-3-lifecycle-hooks-with-real-time-example-1b772b89e085">Vue 3 lifecycle hooks with real-time example</a></li><li><a href="https://blog.canopas.com/golang-unit-tests-with-test-gin-context-80e1ac04adcd">Golang: Unit tests with test gin context</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c76bb011426" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-write-e2e-tests-for-next-js-application-using-playwright-1c76bb011426">How to write E2E tests for Next.js Application using Playwright</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics: A Boon for Strongly Typed Languages]]></title>
            <link>https://medium.com/canopas/generics-a-boon-for-strongly-typed-languages-bbb18f0ed04a?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbb18f0ed04a</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 12:00:29 GMT</pubDate>
            <atom:updated>2024-07-03T10:45:17.836Z</atom:updated>
            <content:encoded><![CDATA[<h4>Get to know when generics are useful and how Golang uses them…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVU9xijGoKTDmd0wFu0uXg.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">home</a>! 🚀</blockquote><h3>Background</h3><p><em>Consider a scenario, You have two glasses one with milk and the other with buttermilk. Your task is to identify between milk and buttermilk before drinking it(of course without tasting and touching!).</em></p><p>Hard to admit that, right? Just because they seem similar doesn’t mean they are the same.</p><p>The same happens with loosely typed languages. When we provide arguments without mentioning types (as they don’t expect), the identification relies on runtime whether it will be a number or string(milk and buttermilk in the above example).</p><p><em>For example, You have a function that accepts a variable as input. Still, unless we specify its type, we can’t admit that it will always be a number or a string because it can be either one or completely a different one — boolean!</em></p><p>There come the strictly/strongly typed languages in the picture. No doubt loosely typed languages come with more freedom but with the cost of robustness!</p><p>In languages like JavaScript and PHP, variables dance to the beat of their assigned values, morphing from numbers to strings with nary a complaint.</p><p>But for those who’ve migrated to Golang, the world of strict typing can feel…well, a bit rigid at first.</p><p>Two separate functions for int and string? <br>Even though having the same computation logic? <br>Where&#39;s the flexibility?</p><blockquote>But why to fear, when generics are here?</blockquote><p>Generics are important for writing reusable and expressive code. In strongly typed languages, generics are a way to go. However, Golang had no support for generics until Go1.17, it started supporting from Go1.18 and later.</p><p>In this blog, we will explore what are the disadvantages of loosely typed languages and how generics bridges a gap between the expressiveness of loose typing and strongly typed languages(Golang).</p><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Why choose strongly typed language over loosely typed?</h3><h4>Loose Typing: Case of the Miscalculated Discount (PHP)</h4><p>Imagine an e-commerce website built with PHP, a loosely typed language. A function calculates a discount based on a user’s loyalty points stored in a variable $points.</p><pre>function calculateDiscount($points) {<br>  if ($points &gt; 100) {<br>    $discount = $points * 0.1; // Assuming points are integers<br>  } else {<br>    $discount = 0;<br>  }<br>  return $discount;<br>}<br><br>$userPoints = &quot;Gold&quot;; // User with &quot;Gold&quot; loyalty tier<br><br>$discount = calculateDiscount($userPoints); // Unexpected behavior<br><br>// This might result in a runtime error or unexpected discount calculation <br>// due to the string value in $userPoints.</pre><p>Here, the function expects an integer for $points to calculate the discount. However, due to loose typing, a string value (&quot;Gold&quot;) is passed.</p><p>This might lead to a runtime error(as it’s not pre-compiled) or an unexpected discount calculation, causing confusion for the user and requiring additional debugging efforts.</p><h4><strong>Strict Typing: Catching the Discount Error Early (Go)</strong></h4><p>Now, let’s consider the same scenario in Go, a strictly typed language.</p><pre>func calculateDiscount(points int) float64 {<br>  if points &gt; 100 {<br>    return float64(points) * 0.1<br>  }<br>  return 0<br>}<br><br>var userPoints int = 150 // User&#39;s loyalty points stored as an integer<br><br>discount := calculateDiscount(userPoints)<br><br>// This code will not compile due to the incompatible type of &quot;userPoints&quot;<br>// if it&#39;s not declared as an integer initially.</pre><p>In Go, the function calculateDiscount explicitly requires an integer for points.</p><p>If we attempt to pass the string value &quot;Gold&quot;, the code won&#39;t even compile. This early error detection prevents unexpected behavior at runtime and ensures data integrity.</p><p>However, while strictly typed languages don’t provide as much flexibility as loosely typed it ensures the robustness of our code. While not being so rigid, strictly typed languages provide support for generics to ensure code reusability and cleanliness.</p><h3>What are generics?</h3><p>Generics are a powerful programming concept that allows you to write functions and data structures that can work with a variety of different data types without sacrificing type safety.</p><h3>Practical use case</h3><p>Let’s consider a simple example,</p><p>A function that takes an array as input be it []int64 or []float64 and returns the sum of all its elements.</p><p>Ideally, we would need to define two different functions for each.</p><pre>// SumInts adds together the values of m.<br>func SumInts(m []int64) int64 {<br> var s int64<br> for _, v := range m {<br>  s += v<br> }<br> return s<br>}<br><br>// SumFloats adds together the values of m.<br>func SumFloats(m []float64) float64 {<br> var s float64<br> for _, v := range m {<br>  s += v<br> }<br> return s<br>}</pre><p>With generics, it’s possible to use a single function that behaves the same for different data types.</p><pre>// SumIntsOrFloats sums the values of map m. It supports both int64 and float64<br>// as types for array values.<br>func SumIntsOrFloats[T int64 | float64](m []T) T{<br> var s T<br> for _, t:= range m {<br>  s += t<br> }<br> return s<br>}</pre><p>This function takes []T as input and give T as output, it can be any of the two we mentioned int64 or float64.</p><p>The magic lies in the T placeholder. It represents a generic type that can be anything int64 or float64. This eliminates the need for duplicate functions and keeps our code clean and concise.</p><h3>Type Constraints in Go Generics</h3><p>Go generics introduce type parameters, allowing functions and data structures to work with various types. However, sometimes, we need to ensure specific properties for those types. This is where type constraints come in.</p><p><strong>The </strong><strong>comparable Constraint: Not for Ordering</strong></p><p>The comparable constraint is a natural choice for ordering elements.</p><p>After all, it guarantees types can be compared for equality using the == operator. However, comparable doesn&#39;t imply the ability to use comparison operators like &lt;, &gt;, &lt;=, and &gt;=.</p><p>Example:</p><pre>func IntArrayContains(arr []int, target int) bool {<br>  for _, element := range arr {<br>    if element == target {<br>      return true<br>    }<br>  }<br>  return false<br>}<br><br>func StringArrayContains(arr []string, target string) bool {<br>  for _, element := range arr {<br>    if element == target {<br>      return true<br>    }<br>  }<br>  return false<br>}</pre><p>The above function takes int and string respectively and checks whether an element exists in an array or not.</p><pre>func ArrayContains[T comparable](arr []T, target T) bool {<br>  for _, element := range arr {<br>    if element == target {<br>      return true<br>    }<br>  }<br>  return false<br>}</pre><p>The above generic function is a replacement if the IntArrayContains() and StringArrayContains() . It can also be used for float(Try providing ([]float64{2.3,4.5,1.2}, 4.5) as argument!</p><p>Where,</p><p><strong>[T comparable]</strong> —defines a generic type parameter T with comparable constraint. This ensures the elements in the slice can be compared using the == operator.</p><p><strong>— The </strong><strong>ordered Constraint: For Ordering</strong></p><p>For ordering elements within a generic function, Go offers the <a href="https://pkg.go.dev/cmp#Ordered">Ordered</a> constraint from the <a href="https://pkg.go.dev/cmp">cmp</a> package.</p><p>The Ordered constraint ensures the type parameter can be used with comparison operators like &lt;, &gt;, &lt;=, and &gt;=, making functions like Min or Maxpossible.</p><p>Example:</p><p>A function to find the minimum value in a slice. Traditionally, we might have written separate functions for different types like int and string .</p><pre>func minInt(s []int) int {<br>  min := s[0]<br>  for _, val := range s {<br>    if val &lt; min {<br>      min = val<br>    }<br>  }<br>  return min<br>}<br><br>func minString(s []string) string {<br>  min := s[0]<br>  for _, val := range s {<br>    if val &lt; min { // String comparison might not be intuitive<br>      min = val<br>    }<br>  }<br>  return min<br>}</pre><p>With generics, we can define a single generic function Min that works with any comparable type.</p><pre>import &quot;cmp&quot;<br><br>func Min[T cmp.Ordered](s []T) T {<br> min := s[0]<br> for _, val := range s {<br>  if val &lt; min {<br>   min = val<br>  }<br> }<br> return min<br>}</pre><p><strong>[T cmp.Ordered]</strong> — It defines a generic type parameter T. The cmp.Ordered part specifies a constraint on T. It must be a type that implements the Ordered interface (meaning it supports comparison operators like &lt;, &gt; etc).</p><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/generics-a-boon-for-strongly-typed-languages-bbb18f0ed04a"><strong><em>this blog</em></strong></a><strong><em>.</em></strong></blockquote><h3>Similar Blogs</h3><ul><li><a href="https://medium.com/canopas/how-to-use-enums-in-golang-ff682b927f0d">How to use Enums in Golang</a></li><li><a href="https://medium.com/canopas/how-to-use-enums-in-golang-ff682b927f0d">How to use Enums in Golang</a></li><li><a href="https://blog.canopas.com/golang-14-shorthand-tricks-you-might-not-know-8d8d21954c49">Golang: 14 Shorthand Tricks You Might Not Know!</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbb18f0ed04a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/generics-a-boon-for-strongly-typed-languages-bbb18f0ed04a">Generics: A Boon for Strongly Typed Languages</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Websocket Alternative: How to use Firestore to Listen to Realtime Events]]></title>
            <link>https://medium.com/canopas/websocket-alternative-how-to-use-firestore-to-listen-to-realtime-events-141e634d04bc?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/141e634d04bc</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[firebaserealtimedatabase]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Fri, 17 May 2024 12:04:54 GMT</pubDate>
            <atom:updated>2024-05-18T09:24:15.272Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore a way to keep all the frontends informed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QksZmD2P1M6p4lglvZ5pRw.png" /><figcaption>Image by <a href="https://canopas.com/">canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">home</a>! 🚀</blockquote><h3>Background</h3><p>Imagine you’re building a real-time chat application where users can communicate instantly with each other, or a collaborative document editing tool similar to Google Docs.</p><p>In such applications, changes made by one user must be immediately reflected for all other users. Websockets can do that for us, but then we need to dive into managing different events that are being exchanged between two clients (for ex. A mobile application and a web app).</p><p>Ah, you got it right! Firestore, a NoSQL document database from Firebase, offers excellent real-time capabilities, and integrating it with Vue 3 can help us achieve the desired real-time functionality seamlessly.</p><p>In this blog, we’ll walk through how to configure Firestore to listen to real-time events in a Vue 3 application. We’ll explore a practical example, discuss potential applications, and provide detailed code examples to demonstrate how two different apps can listen and respond to each other’s events.</p><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Scenarios and Applications</h3><p>Before diving into the code, let’s consider some real-world scenarios where real-time event listening is indeed needed.</p><ol><li><strong>Real-Time Chat Applications</strong>: Users can send and receive messages instantly without refreshing the page.</li><li><strong>Collaborative Editing Tools</strong>: Multiple users can edit documents simultaneously, with changes reflected in real time.</li><li><strong>Live Sports Updates</strong>: Fans can receive live scores and updates during a game.</li><li><strong>Stock Market Dashboards</strong>: Investors can see live price updates and market changes as they happen.</li></ol><p>These scenarios underscore the importance of real-time data synchronization, making Firestore a perfect match.</p><h3>Why Choose Firestore Over WebSockets?</h3><p>While WebSockets are a powerful technology for real-time communication, Firestore offers several advantages that make it a better choice for many applications.</p><ul><li><strong>Simplicity</strong>: Firestore provides a higher-level API that simplifies the implementation of real-time updates, reducing the complexity of managing socket connections and message parsing.</li><li><strong>Scalability</strong>: Firestore automatically scales with your application’s usage, handling large numbers of concurrent connections and data without requiring extensive infrastructure management.</li><li><strong>Offline Support</strong>: Firestore has built-in offline data persistence, allowing applications to function even when the user is offline and synchronize changes when connectivity is restored.</li><li><strong>Security</strong>: Firestore integrates seamlessly with Firebase Authentication and Firebase Security Rules, making managing user authentication and data access controls easier.</li><li><strong>Integration</strong>: Firestore is part of the Firebase ecosystem, providing easy integration with other Firebase services like Cloud Functions, Cloud Messaging, and Analytics.</li></ul><h3>Prerequisites</h3><ul><li>A Vue.js app</li><li>The Firebase project along with the Firestore setup</li></ul><blockquote><em>I’m assuming that you’ve already set up a Firebase project and Firestore database. Let’s move toward implementation. Consider having a look at How to configure </em><a href="https://firebase.google.com/docs/firestore/quickstart"><em>Firestore</em></a><em>, if not.</em></blockquote><p>To better understand, we will implement two different Vue apps that will listen to events from each other. On a side note, Any of them or both can be replaced with another client like a Mobile application.</p><ul><li><strong>First app is being used by Alex</strong></li><li><strong>Second app is being used by Bob</strong></li></ul><p>Let’s create the first app <strong>Alex(For Alex)</strong> and we will create a similar second app <strong>Bob(For Bob)</strong> later.</p><h3>Configure Firestore</h3><h4>Install Firebase in the Vue project</h4><pre>npm install firebase</pre><h4>Configure Firestore in Vue 3</h4><p>Create a firebase.js file in the src directory to initialize Firestore and add the code below. <br>P.S. Don’t forget to replace the placeholder strings with your actual Firebase configuration values.</p><pre>// src/firebase.js<br><br>import { initializeApp } from &#39;firebase/app&#39;;<br>import { getFirestore } from &#39;firebase/firestore&#39;;<br><br>const firebaseConfig = {<br>  apiKey: &quot;YOUR_API_KEY&quot;,<br>  authDomain: &quot;YOUR_AUTH_DOMAIN&quot;,<br>  projectId: &quot;YOUR_PROJECT_ID&quot;,<br>  storageBucket: &quot;YOUR_STORAGE_BUCKET&quot;,<br>  messagingSenderId: &quot;YOUR_MESSAGING_SENDER_ID&quot;,<br>  appId: &quot;YOUR_APP_ID&quot;<br>};<br><br>// Initialize Firebase<br>const app = initializeApp(firebaseConfig);<br>const db = getFirestore(app);<br><br>export { db };</pre><ul><li>The code above initializes the Firebase app and Firestore instance, which can be used at other places.</li></ul><h3>Create collection</h3><p>Create collection messages in the Firestore. The document fields will be,</p><ul><li>id (string) -&gt; unique identifier(random)</li><li>text (string)-&gt; message from a user</li><li>user(string) -&gt; name of the sender (Alex or Bob)</li><li>created_at(timestamp) -&gt; message sent date-time</li></ul><p>The collection should look like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZVmrnEQH6G3dLD-5b_LYw.png" /><figcaption>structure of <strong>message</strong> collection</figcaption></figure><h3>Configure Chat app</h3><p><em>Remove all the code from </em><strong><em>App.vue</em></strong><em> and routes from </em><strong><em>index.js</em></strong><em>. Add below code in App.vue.</em></p><h4>Display all messages</h4><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Alex&#39;s device&lt;/h1&gt;<br>    &lt;ul&gt;<br>      &lt;li v-for=&quot;message in messages&quot; :key=&quot;message.id&quot;&gt;<br>        {{ message.user }} : {{ message.text }}<br>      &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import {<br>  collection,<br>  query,<br>  orderBy,<br>  getDocs,<br>} from &quot;firebase/firestore&quot;;<br>import { db } from &quot;./firebase&quot;;<br>import { ref, onMounted } from &quot;vue&quot;;<br><br>const messages = ref([]);<br><br>onMounted(async () =&gt; {<br>  // fetches all the &quot;messages&quot; in ascending order of created_at<br>  const q = query(collection(db, &quot;messages&quot;), orderBy(&quot;created_at&quot;));<br>  const querySnapshot = await getDocs(q);<br>  messages.value = querySnapshot.docs.map((doc) =&gt; ({<br>    id: doc.id,<br>    text: doc.data().text,<br>    user: doc.data().user,<br>  }));<br>});<br>&lt;/script&gt;<br><br>&lt;style scoped&gt;<br>ul {<br>  list-style-type: none;<br>  padding: 0;<br>}<br><br>li {<br>  background: #f1f1f1;<br>  margin: 5px 0;<br>  padding: 10px;<br>  border-radius: 5px;<br>}<br>&lt;/style&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*lddXI_1qJrLnHX1-DkgrrQ.png" /><figcaption>Show all the messages</figcaption></figure><h4>Send new message</h4><p>Let’s add an input field through which the user can send a new message in chat.</p><p>Add the below code after &lt;li&gt;&lt;/li&gt; . Add styles in the styles section.</p><pre>&lt;input v-model=&quot;newMessage&quot; @keyup.enter=&quot;sendMessage&quot; placeholder=&quot;Type a message&quot; /&gt;<br>&lt;button @click=&quot;sendMessage&quot;&gt;Send&lt;/button&gt;<br><br>&lt;style&gt;<br>  input {<br>  padding: 10px;<br>  box-sizing: border-box;<br>}<br><br>button {<br>  padding: 10px;<br>  background: #007bff;<br>  color: white;<br>  border: none;<br>  border-radius: 5px;<br>  cursor: pointer;<br>  margin-left: 10px;<br>}<br>&lt;/style&gt;</pre><p>Update the &lt;script&gt;&lt;/script&gt; section as below, it will manage sending and adding messages to the collection messages .</p><pre>&lt;script setup&gt;<br>import {<br>  collection,<br>  query,<br>  orderBy,<br>  addDoc,<br>  getDocs,<br>} from &quot;firebase/firestore&quot;;<br>import { db } from &quot;./firebase&quot;;<br>import { ref, onMounted } from &quot;vue&quot;;<br><br>const messages = ref([]); // empty list<br>const newMessage = ref(&quot;&quot;); // empty new message<br><br>onMounted(async() =&gt; {<br>  const q = query(collection(db, &quot;messages&quot;), orderBy(&quot;created_at&quot;));<br>  const querySnapshot = await getDocs(q); // fetch messages in the ascending order of created_at<br>  messages.value = querySnapshot.docs.map(doc =&gt; ({ id: doc.id, text: doc.data().text, user: doc.data().user }));<br>});<br><br>// save message to &quot;messages&quot; collection<br>const sendMessage = async () =&gt; {<br>  if (newMessage.value.trim()) {<br>    await addDoc(collection(db, &quot;messages&quot;), {<br>      text: newMessage.value,<br>      user: &quot;Alex&quot;,<br>      created_at: new Date(),<br>    });<br>    newMessage.value = &quot;&quot;;<br>  }<br>};<br>&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*ii6CEGSLdNZYxvstGx-BGA.gif" /><figcaption>Send new message</figcaption></figure><h4>Listen to real-time events</h4><p>Here comes a twist in the story. Until now we fetched messages and added new messages. Now we want to catch real updates on the messages collection.</p><p>That means when any document is added/updated in the messages collection it will receive an event to update the existing data. Don’t worry! It’s not rocket science😅.</p><p>For listening events, there’s a method <strong>onSnapShot, </strong>we will replace our current <strong>getDocs</strong> method as onSnapShot can manage fetching and listening.</p><p>Refer to the <a href="https://firebase.google.com/docs/firestore/query-data/listen">Firebase Firestore Guide</a> for more details.</p><h4><strong>Add the below code to App.vue</strong></h4><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;h1&gt;Alex&#39;s device&lt;/h1&gt;<br>    &lt;ul&gt;<br>      &lt;li v-for=&quot;message in messages&quot; :key=&quot;message.id&quot;&gt;<br>        {{ message.user }} : {{ message.text }}<br>      &lt;/li&gt;<br>    &lt;/ul&gt;<br>    &lt;input<br>      v-model=&quot;newMessage&quot;<br>      @keyup.enter=&quot;sendMessage&quot;<br>      placeholder=&quot;Type a message&quot;<br>    /&gt;<br>    &lt;button @click=&quot;sendMessage&quot;&gt;Send&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import {<br>  collection,<br>  query,<br>  orderBy,<br>  addDoc,<br>  onSnapshot,<br>} from &quot;firebase/firestore&quot;;<br>import { db } from &quot;./firebase&quot;;<br>import { ref, onMounted } from &quot;vue&quot;;<br><br>const messages = ref([]); // empty list<br>const newMessage = ref(&quot;&quot;); // empty new message<br><br>onMounted(() =&gt; {<br>  const q = query(collection(db, &quot;messages&quot;), orderBy(&quot;created_at&quot;));<br>  onSnapshot(q, (snapshot) =&gt; { // listen to realtime events and fetch messages<br>    messages.value = snapshot.docs.map((doc) =&gt; ({<br>      id: doc.id,<br>      text: doc.data().text,<br>      user: doc.data().user,<br>    }));<br>  });<br>});<br><br>// sends new message<br>const sendMessage = async () =&gt; {<br>  if (newMessage.value.trim()) {<br>    await addDoc(collection(db, &quot;messages&quot;), {<br>      text: newMessage.value,<br>      user: &quot;Alex&quot;,<br>      created_at: new Date(),<br>    });<br>    newMessage.value = &quot;&quot;;<br>  }<br>};<br>&lt;/script&gt;<br><br>&lt;style scoped&gt;<br>ul {<br>  list-style-type: none;<br>  padding: 0;<br>}<br><br>li {<br>  background: #f1f1f1;<br>  margin: 5px 0;<br>  padding: 10px;<br>  border-radius: 5px;<br>}<br><br>input {<br>  padding: 10px;<br>  box-sizing: border-box;<br>}<br><br>button {<br>  padding: 10px;<br>  background: #007bff;<br>  color: white;<br>  border: none;<br>  border-radius: 5px;<br>  cursor: pointer;<br>  margin-left: 10px;<br>}<br>&lt;/style&gt;</pre><h3>Create an App for Bob</h3><p>You can create the same Vue app for <strong>Bob</strong> as <strong>Alex</strong>, or you can create an app on other platforms too like mobile.</p><p>For now, Copy the <strong>Alex</strong> app and create the same app named <strong>Bob</strong>. Replace <strong>Alex</strong> with <strong>Bob</strong> everywhere in the App.vue. It’s that simple!</p><p>Let’s run both apps…</p><p>Yay! We have our chat apps handy 🎉. You will find the chat interfaces below. Let’s check if it works in real.</p><ul><li>Update the document data directly inside the collection</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9JVwgNZw4FUFKX3ndfk9Q.gif" /><figcaption>Updating document fields reflects the change</figcaption></figure><ul><li>Add new documents to the collection</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZyZhfzq1Rw2-Grn85YlAg.gif" /><figcaption>Chat apps</figcaption></figure><p>In this blog, we have created two web apps only, but similar can be done for web and mobile combo or two mobile apps as well.</p><h3>Conclusion</h3><ul><li>Integrating Firestore for real-time events listening opens up a world of possibilities for building dynamic, responsive applications.</li><li>From chat apps to collaborative tools, real-time data synchronization ensures that users have the most up-to-date information without needing to refresh their pages.</li><li>Firestore offers a robust, scalable, and easy-to-use solution for real-time applications, making it a compelling alternative to WebSockets.</li><li>Its simplicity, offline support, built-in security, and seamless integration with the Firebase ecosystem can significantly speed up development and enhance your application’s functionality.</li></ul><p>In this blog, we went through how to set up Firestore, with the Vue project to listen to real-time events, and even create two different applications that can communicate through Firestore.</p><p>So, go ahead and start building your next real-time application with Firestore and your favorite platform. The sky’s the limit!</p><h3>References</h3><ul><li>How to add the Firebase project in the app — <a href="https://firebase.google.com/docs/web/setup">https://firebase.google.com/docs/web/setup</a></li><li>What is Firestore? — <a href="https://firebase.google.com/docs/firestore">https://firebase.google.com/docs/firestore</a></li><li>Basic CRUD operations with Firestore — <a href="https://firebase.google.com/docs/firestore/quickstart">https://firebase.google.com/docs/firestore/quickstart</a></li><li>Real-time event listening — <a href="https://firebase.google.com/docs/firestore/query-data/listen">https://firebase.google.com/docs/firestore/query-data/listen</a></li></ul><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/websocket-alternative-how-to-use-firestore-to-listen-to-realtime-events-141e634d04bc"><strong><em>this blog</em></strong></a><em>.</em></blockquote><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=141e634d04bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/websocket-alternative-how-to-use-firestore-to-listen-to-realtime-events-141e634d04bc">Websocket Alternative: How to use Firestore to Listen to Realtime Events</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Types and Higher-Order Functions in Go]]></title>
            <link>https://medium.com/canopas/function-types-and-higher-order-functions-in-go-8ea2e95d1860?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ea2e95d1860</guid>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[advanced-concepts]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Thu, 09 May 2024 14:03:33 GMT</pubDate>
            <atom:updated>2024-05-09T14:08:28.763Z</atom:updated>
            <content:encoded><![CDATA[<h4>One of the ways to make your code more readable and effective…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCMD_kF2NqKGLcVpG0yhsw.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">home</a>! 🚀</blockquote><h3>Background</h3><p>In the world of programming, the ability to treat functions as first-class citizens opens up a plethora of possibilities.</p><p>Go, with its support for first-class functions and function types, empowers developers to write cleaner, more modular, and flexible code.</p><blockquote><em>When we say, </em><strong><em>functions are considered first-class citizens</em></strong><em>, we mean it.</em></blockquote><blockquote><em>It means they can be assigned to variables, passed as arguments to other functions, and returned from functions. This capability stems from the ability to define function types.</em></blockquote><p>In this blog post, we’ll delve into the concepts of function types and higher-order functions in Go, exploring how they can be defined, utilized, and leveraged to enhance the efficiency and readability of your codebase.</p><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>What are higher-order functions?</h3><p>Higher-order functions are functions that either take other functions as arguments, return functions, or both. They enable developers to write more generic and reusable code.</p><p>Let’s explore the use cases where we can use higher-order functions.</p><h3>Callbacks</h3><p>Suppose we have a function that performs some operation on each element of a list.</p><p>This function can use another function as an argument that performs the desired operation on the list, instead of directly performing it from the function.</p><p>It can be a better candidate when we want to perform different operations in the same function based on conditions.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func Process(list []int, callback func(int)) {<br>    for _, item := range list {<br>        callback(item)<br>    }<br>}<br><br>func main() {<br>    numbers := []int{1, 2, 3, 4, 5}<br>    Process(numbers, func(num int) {<br>        fmt.Println(num * 2)<br>    })<br>}<br><br>// Output<br>2<br>4<br>6<br>8<br>10</pre><h3>Anonymous Functions</h3><p>Anonymous functions can be used inline wherever a function value is expected. <br>For example, sorting strings by their length using an anonymous function.</p><pre>package main<br><br>import (<br>  &quot;sort&quot;<br>  &quot;fmt&quot;<br>)<br><br>func main() {<br>    words := []string{&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;grape&quot;}<br>    sort.Slice(words, func(i, j int) bool {<br>        return len(words[i]) &lt; len(words[j])<br>    })<br>    fmt.Println(words) // Output: [apple grape banana orange]<br>}</pre><p><strong>Advantage:</strong> It offers a concise and flexible way to define functions inline, eliminating the need for separate function declarations.</p><h3>Closure</h3><p>Closures capture the surrounding state, allowing for the encapsulation of variables. <br>Here’s an example where a closure is used to maintain state across multiple invocations:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func counter() func() int {<br>    count := 0<br>    return func() int {<br>        count++<br>        return count<br>    }<br>}<br><br>func main() {<br>    increment := counter()<br>    fmt.Println(increment()) // Output: 1<br>    fmt.Println(increment()) // Output: 2<br>    fmt.Println(increment()) // Output: 3<br>}</pre><p><strong>Advantage:</strong> It enables the creation of self-contained units of functionality that retain access to their surrounding lexical scope.</p><p>Closures ensure the scope and lifetime of variables captured within them are preserved for the duration of their existence.</p><h3>Function Composition</h3><p>Function composition involves combining multiple functions to create a new one. <br>Here’s an example where two functions are composed to form a new one.</p><pre><br>package main<br><br>import &quot;fmt&quot;<br><br>func addOne(num int) int {<br>    return num + 1<br>}<br><br>func double(num int) int {<br>    return num * 2<br>}<br><br>func main() {<br>    addOneThenDouble := func(num int) int {<br>        return double(addOne(num))<br>    }<br><br>    result := addOneThenDouble(5)<br>    fmt.Println(result) // Output: 12<br>}</pre><p><strong>Advantage:</strong> It empowers developers to create complex behaviors by combining simple functions in a modular and composable manner.</p><h3>Error Handling</h3><p>Higher-order functions can be used to propagate errors. <br>Here’s an example where a higher-order function is used to wrap a function and handle errors.</p><pre>package main<br><br>import (<br> &quot;errors&quot;<br> &quot;fmt&quot;<br>)<br><br>func handleErrors(fn func() error) error {<br> if err := fn(); err != nil {<br>  return fmt.Errorf(&quot;error occurred: %v&quot;, err)<br> }<br> return nil<br>}<br><br>func main() {<br> err := handleErrors(func() error {<br>  // Simulating an operation that may return an error<br>  return errors.New(&quot;something went wrong&quot;)<br> })<br> if err != nil {<br>  fmt.Println(&quot;Error handled:&quot;, err)<br> } else {<br>  fmt.Println(&quot;No error occurred&quot;)<br> }<br>}<br><br>// Output<br>Error handled: error occurred: something went wrong</pre><h3>Testing</h3><p>Mocking functions for testing can be achieved using higher-order functions. <br>Here’s an example where a mock function is passed to a function under test.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type DependencyFunc func(int) int<br><br>func FunctionUnderTest(dep DependencyFunc, num int) int {<br>    return dep(num) * 2<br>}<br><br>func main() {<br>    result := FunctionUnderTest(func(num int) int {<br>        return num + 1 // Mocked dependency<br>    }, 5)<br>    fmt.Println(result) // Output: 12<br>}</pre><p><strong>Advantage:</strong> It facilitates developers to write comprehensive tests for functions that accept or return other functions, ensuring the correctness and reliability of their code.</p><p>Major usability is when we want different outputs from the same function, depending upon the environment or according to the condition.</p><h3>Performance Considerations</h3><p>Performance can be optimized by minimizing unnecessary function calls. Here’s an example where a closure is used to reduce overhead.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    sum := 0<br>    add := func(num int) {<br>        sum += num<br>    }<br><br>    for i := 0; i &lt; 100; i++ {<br>        add(i)<br>    }<br><br>    fmt.Println(sum) // Output: 4950<br>}</pre><p><strong>Advantage:</strong> It improves the efficiency and responsiveness of applications, particularly in performance-critical scenarios, by minimizing overhead and maximizing resource utilization.</p><h3>Compatibility and Interoperability</h3><p>Function types can be used with interfaces for compatibility. <br>Here’s an example where an interface is defined to work with different function types.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Operator interface {<br>    Operate(int, int) int<br>}<br><br>type Adder struct{}<br><br>func (a Adder) Operate(x, y int) int {<br>    return x + y<br>}<br><br>type Multiplier struct{}<br><br>func (m Multiplier) Operate(x, y int) int {<br>    return x * y<br>}<br><br>func main() {<br>    var op Operator<br>    op = Adder{}<br>    fmt.Println(op.Operate(2, 3)) // Output: 5<br><br>    op = Multiplier{}<br>    fmt.Println(op.Operate(2, 3)) // Output: 6<br>}</pre><p><strong>Advantage:</strong> It addresses considerations for integrating function types and higher-order functions with other language features, such as interfaces, structs, and generics.</p><blockquote>With that said, Every coins has two sides. Higher-order functions can also have some performance impact depending upon the several factors.</blockquote><p>It’s recommended to use the higher-order function depending upon the requirements more often. Let’s discuss some of the negative impacts it can have on performance.</p><h4>Function Call Overhead</h4><p>Each function call incurs some overhead, including parameter passing, stack manipulation, and return address management.</p><p>When using higher-order functions that accept or return functions, there may be additional overhead associated with passing function pointers or closures.</p><h4>Closure Overhead</h4><p>Closures, which capture the surrounding lexical scope, typically involve additional memory allocation and runtime overhead.</p><p>This overhead increases with the size and complexity of the captured variables and can impact performance, especially in scenarios where closures are created frequently or used in tight loops.</p><h3>Conclusion</h3><p>Higher-order functions either take other functions as arguments, return functions or can be used with interfaces and generics.</p><p>It provides a facility to reuse the code and manipulate the code behavior in between the executions, mocking the necessary dependencies or functionality.</p><p>Higher-order functions, while powerful and flexible, can have an impact on performance due to the overhead involved in function calls and closures.</p><p>However, the extent of this impact depends on various factors such as the frequency of function calls, the complexity of the functions involved, and the efficiency of the compiler optimizations.</p><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/function-types-and-higher-order-functions-in-go-8ea2e95d1860"><strong><em>this blog</em></strong></a><em>.</em></blockquote><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ea2e95d1860" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/function-types-and-higher-order-functions-in-go-8ea2e95d1860">Function Types and Higher-Order Functions in Go</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Enums in Golang]]></title>
            <link>https://medium.com/canopas/how-to-use-enums-in-golang-ff682b927f0d?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff682b927f0d</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[enumeration]]></category>
            <category><![CDATA[enum]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 10:34:08 GMT</pubDate>
            <atom:updated>2024-03-28T13:25:58.503Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring ways of creating Enums using iota identifier and struct tags</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mk0d0rFebVLs0qI0mLys7g.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">home</a>! 🚀</blockquote><h3>Background</h3><p>Imagine you’re building a Todo application using Go. Each task in your application has a status associated with it, indicating whether it’s <strong>“completed”, “archived”</strong> or <strong>“deleted”</strong>.</p><p>As a developer, you want to ensure that only valid status values are accepted when creating or updating tasks via your API endpoints. Additionally, you want to provide clear error messages to users if they attempt to set an invalid status apart from the valid ones.</p><blockquote>Of course, you will say enums, right?</blockquote><p>But the bad news is Go doesn’t provide enums and the good news is we can still implement it.</p><p>In this blog, we’ll explore how to effectively manage enums in Golang, including validation techniques to ensure data integrity and reliability.</p><p>Whether you are a beginner or an experienced developer, this guide aims to demystify enums and empower you to leverage their power in your Go projects.</p><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>What is Enum?</h3><p>Enum is a short form of enumeration, which represents a distinct set of named constants. While languages like Java and C++ offer native support for enums, Go takes a different approach.</p><p>Instead of a dedicated enum type, Go developers use constants or custom types with iota to emulate enum-like behavior. Let’s begin!</p><h3>Why Enums?</h3><ul><li>Enums make code more readable by providing descriptive names for values, rather than using raw integer or string constants. This enhances code clarity and makes it easier for other developers to understand and maintain the codebase.</li><li>Enums provide compile-time checking, which helps catch errors early in the development process. This prevents invalid or unexpected values from being assigned to variables, reducing the likelihood of runtime errors.</li><li>By restricting the possible values a variable can hold to a predefined set, enums help prevent logic errors caused by incorrect or unexpected values.</li></ul><h3>Defining Enums with Constants</h3><p>Constants are a straightforward way to define enums in Go. Let’s consider a basic example where we define enum constants representing different days of the week.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>const (<br>    SUNDAY    = &quot;Sunday&quot;<br>    MONDAY    = &quot;Monday&quot;<br>    TUESDAY   = &quot;Tuesday&quot;<br>    WEDNESDAY = &quot;Wednesday&quot;<br>    THURSDAY  = &quot;Thursday&quot;<br>    FRIDAY    = &quot;Friday&quot;<br>    SATURDAY  = &quot;Saturday&quot;<br>)<br><br>func main() {<br>    day := MONDAY<br>    fmt.Println(&quot;Today is &quot;, day) // &quot;Today is Monday&quot;<br>}</pre><h3>Simulating Enums with Custom Types and iota</h3><p>While constants work well for simple enums, custom types with iota provide a more idiomatic approach in Go.</p><h4>What is iota?</h4><p>iota is a special identifier in Go that is used with const declarations to generate a sequence of related values automatically.</p><p>It simplifies the process of defining sequential values, particularly when defining enums or declaring sets of constants with incrementing values.</p><p>When iota is used in a const declaration, it <strong>starts with the value 0 and increments by 1 for each subsequent occurrence</strong> within the same const block. If iota appears in multiple const declarations within the same block, its value is reset to 0 for each new const block.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>const (<br>    SUNDAY = iota // SUNDAY is assigned 0<br>    MONDAY        // MONDAY is assigned 1 (incremented from SUNDAY)<br>    TUESDAY       // TUESDAY is assigned 2 (incremented from MONDAY)<br>    WEDNESDAY     // WEDNESDAY is assigned 3 (incremented from TUESDAY) <br>    THURSDAY      // THURSDAY is assigned 4 (incremented from WEDNESDAY)<br>    FRIDAY        // FRIDAY is assigned 5 (incremented from THURSDAY)<br>    SATURDAY      // SATURDAY is assigned 6 (incremented from FRIDAY)<br>)<br><br>func main() {<br>    fmt.Println(MONDAY, WEDNESDAY, FRIDAY) // Output: 1 3 5<br>}</pre><p>Let’s rewrite the previous example using a custom type(int).</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type Day int<br><br>const (<br>    Sunday Day = iota<br>    Monday<br>    Tuesday<br>    Wednesday<br>    Thursday<br>    Friday<br>    Saturday<br>)<br><br>func main() {<br>    day := Monday<br>    fmt.Println(&quot;Today is &quot;, day) // Output: Today is 1<br>}</pre><p>In this example, we define a custom-type Day and use iota to auto-increment the values of the constants. This approach is more concise and offers better type safety.</p><p>Optionally, we can also use like iota + 1 , if we want our constants to start from 1.</p><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/how-to-use-enums-in-golang"><strong><em>this blog</em></strong></a><em>.</em></blockquote><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff682b927f0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-use-enums-in-golang-ff682b927f0d">How to use Enums in Golang</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang: 14 Shorthand Tricks You Might Not Know!]]></title>
            <link>https://medium.com/canopas/golang-14-shorthand-tricks-you-might-not-know-8d8d21954c49?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d8d21954c49</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[shortcuts]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 05:13:40 GMT</pubDate>
            <atom:updated>2023-12-11T09:29:23.197Z</atom:updated>
            <content:encoded><![CDATA[<h4>Time-Saving Tricks…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xr1G1KPUSm_4L15h0XG88A.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Are you ready to take your Golang skills to the next level?</blockquote><p>Let’s delve into the realm of time-saving tricks, unveiling a collection of shorthand secrets that will transform the way you code — because programming just got a whole lot cooler!</p><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Table of Contents</h3><pre>1. <a href="#2d8a">Declare And Initialize A Variable In One Line</a><br>2. <a href="#0773">Declare and Initialize Multiple Variables</a><br>3. <a href="#02ca">Swap Values Between Variables</a><br>4. <a href="#148b">Defer a Function Call</a><br>5. <a href="#2edf">Check for Existence in a Map</a><br>6. <a href="#8d31">Loop Over Slices with Index and Value</a><br>7. <a href="#da85">Check for Errors</a><br>8. <a href="#81e7">Initialize A Variable With Zero-Value</a><br>9. <a href="#77dd">Create a Pointer to a Variable</a><br>10. <a href="#3fe2">Anonymous Functions</a><br>11. <a href="#6489">Create and Initialize Struct Instance At Once</a><br>12. <a href="#a2b3">Append Multiple Values To A Slice</a><br>13. <a href="#b9e2">Create and Initialize Maps At Onc</a>e<br>14. <a href="#c935">Define Multiple Constants</a><br>* <a href="#30a0">Wrapping up</a></pre><h3>1. Declare And Initialize A Variable In One Line</h3><pre>// Long form<br>var message string<br>message = &quot;Hello, Golang!&quot;<br><br>// Shorthand<br>message := &quot;Hello, Golang!&quot;</pre><p><strong>Benefit: </strong>This shorthand not only reduces redundancy but also enhances code readability, making it a go-to technique for efficient variable handling.</p><p><strong>Use Case:</strong> Whether it’s initializing loop counters, capturing return values, or setting up quick variables, this shorthand trick proves invaluable for cleaner and more expressive code.</p><h3>2. Declare and Initialize Multiple Variables</h3><pre>// Long form<br>var a, b, c int<br>a = 1<br>b = 2<br>c = 3<br><br>// Shorthand<br>a, b, c := 1, 2, 3</pre><p><strong>Benefit:</strong> Declaring and initializing multiple variables in a single line enhances code clarity and reduces redundancy.</p><p><strong>Use Case:</strong> Whether it’s setting up multiple flags, configuring different parameters, or initializing counters in a loop, this shorthand trick simplifies the process and enhances the overall readability of your code.</p><h3>3. Swap Values Between Variables</h3><pre>a, b := 1, 2<br><br>// Long form<br>temp := a<br>a = b<br>b = temp<br><br>// Shorthand<br>a, b = b, a</pre><p><strong>Benefit: </strong>This shorthand trick eliminates the need for a temporary variable, bringing simplicity and clarity to your code.</p><p><strong>Use Case: </strong>Whether it’s sorting algorithms, toggling between states, or rearranging data, this trick reduces the lines of code needed for a swap operation, resulting in cleaner and more efficient code.</p><h3>4. Defer a Function Call</h3><pre>// Long form<br>func cleanup() {<br>    // Cleanup logic<br>}<br>defer cleanup()<br><br>// Shorthand<br>defer func() {<br>    // Cleanup logic<br>}()</pre><p><strong>Benefit:</strong> This shorthand enhances code readability and ensures that necessary actions are taken at the right time.</p><p><strong>Use Case: </strong>It’s particularly handy for releasing resources, closing files, or handling cleanup operations.</p><p>This shorthand not only simplifies the structure of your code but also promotes more robust and maintainable Golang programs.</p><h3>5. Check for Existence in a Map</h3><pre>// Long form<br>value, exists := myMap[key]<br>if !exists {<br>    // Key doesn&#39;t exist in the map<br>}<br><br>// Shorthand<br>if value, exists := myMap[key]; !exists {<br>    // Key doesn&#39;t exist in the map<br>}</pre><p><strong>Benefit:</strong> Efficiently check if a key exists in a map, simplifying conditional logic for map operations.</p><p><strong>Use Case:</strong> Whether it’s avoiding panics or customizing behavior based on the map content, this idiom enhances the efficiency and clarity of your code.</p><h3>6. Loop Over Slices with Index and Value</h3><pre>// Long form<br>for i := 0; i &lt; len(numbers); i++ {<br>    fmt.Println(i, numbers[i])<br>}<br><br>// Shorthand<br>for i, value := range numbers {<br>    fmt.Println(i, value)<br>}</pre><p><strong>Benefit:</strong> This concise idiom enhances code readability and is particularly useful when you need both the position and the content of each element.</p><p><strong>Use Case: </strong>Whether it’s modifying elements, tracking positions, or performing complex logic based on the index and value, this idiom streamlines the process and makes your code more expressive.</p><h3>7. Check for Errors</h3><pre>// Long form<br>result, err := someFunction()<br>if err != nil {<br>    // Handle the error<br>}<br><br>// Shorthand<br>if result, err := someFunction(); err != nil {<br>    // Handle the error<br>}</pre><p><strong>Benefit:</strong> In error handling, it promotes code clarity and reduces verbosity.</p><p><strong>Use Case:</strong> Whether it’s file operations, network requests, or any function that may return an error, this idiom ensures that error handling is an integral part of your code without sacrificing clarity.</p><h3>8. Initialize A Variable With Zero-Value</h3><pre>// Long form<br>var count int<br><br>// Shorthand<br>count := 0</pre><p>Initialize variables with default zero values, improving code clarity and reducing redundancy.</p><p><strong>Benefit: </strong>By declaring variables without explicitly assigning values, Go allows automatic zero-value assignment, reducing redundancy in your code.</p><p><strong>Use Case: </strong>Whether it’s initializing counters, creating placeholder variables, or setting up default configurations, Golang’s automatic zero-value assignment simplifies the process, making your code more succinct and maintainable.</p><h3>9. Create a Pointer to a Variable</h3><pre>// Long form<br>var x int<br>ptr := &amp;x<br><br>// Shorthand<br>ptr := new(int)</pre><p><strong>Benefit:</strong> The new keyword allows you to declare and initialize a pointer in a single line, enhancing code readability and efficiency.</p><p><strong>Use Case:</strong> When you need to work with pointers in Golang, this shorthand trick is invaluable.</p><p>Whether it’s dynamically allocating memory, passing variables by reference, or creating structures with pointers, this idiom streamlines the process and ensures a more concise representation of your code.</p><h3>10. Anonymous Functions</h3><pre>// Long form<br>func add(x, y int) int {<br>    return x + y<br>}<br><br>// Shorthand<br>add := func(x, y int) int {<br>    return x + y<br>}</pre><p><strong>Benefit:</strong> It allows you to define functions without explicit names, promoting concise and purpose-specific code.</p><p><strong>Use Case:</strong> Anonymous functions are often used for short-lived operations, callbacks, or as arguments to higher-order functions.</p><p>They are perfect for one-off tasks, callbacks in asynchronous operations, or providing functionality on the fly. This shorthand enhances the expressiveness and modularity of your code.</p><h3>11. Create and Initialize Struct Instance At Once</h3><pre>type Person struct {<br>    Name string<br>    Age  int<br>}<br><br>// Long form<br>person : Person{}<br>person.Name = &quot;John&quot;<br>person.Age = 30<br><br>// Shorthand<br>person := Person{Name: &quot;John&quot;, Age: 30}</pre><p><strong>Benefit:</strong> This idiom enhances code clarity and reduces redundancy in Golang programs.</p><p><strong>Use Case: </strong>When dealing with complex data structures represented by structs, initializing them in a single line is efficient.</p><p>Whether it’s defining user profiles, configuring settings, or creating instances of custom types, this shorthand trick streamlines the process, resulting in cleaner and more expressive code.</p><h3>12. Append Multiple Values To A Slice</h3><pre>// Long form<br>numbers := []int{1, 2, 3}<br><br>arr := []int{4, 5, 6}<br><br>for i := range arr {<br>  numbers = append(numbers, arr[i])<br>}<br><br>// Shorthand<br>numbers := []int{1, 2, 3}<br>numbers = append(numbers, []int{4, 5, 6}...)</pre><p><strong>Benefit:</strong> This shorthand streamlines list manipulations and enhances the efficiency of slice operations.</p><p><strong>Use Case:</strong> This is particularly handy when dealing with dynamic datasets or when you want to avoid modifying the original slices.</p><p>Whether it’s building a collection, concatenating slices, or handling dynamic data, the combination of append and ... ensures a concise and expressive representation in your code.</p><h3>13. Create and Initialize Maps At Once</h3><pre>// Long form<br>colors := make(map[string]string)<br>colors[&quot;red&quot;] = &quot;#ff0000&quot;<br>colors[&quot;green&quot;] = &quot;#00ff00&quot;<br><br>// Shorthand<br>colors := map[string]string{<br>    &quot;red&quot;:   &quot;#ff0000&quot;,<br>    &quot;green&quot;: &quot;#00ff00&quot;,<br>}</pre><p><strong>Benefit:</strong> This idiom enhances code readability and simplifies the representation of key-value pairs.</p><p><strong>Use Case:</strong> In scenarios where you need to define and populate a map in one go, this shorthand trick proves highly efficient.</p><h3>14. Define Multiple Constants</h3><pre>// Long form<br>const pi float64 = 3.14159<br>const maxAttempts int = 3<br><br>// Shorthand<br>const (<br>    pi          = 3.14159<br>    maxAttempts = 3<br>)</pre><p><strong>Benefit:</strong> This idiom streamlines the process of grouping related constants. We can define multiple constants within a single const block. This not only improves readability but also helps maintain a consistent style when defining multiple constants.</p><p><strong>Use Case:</strong> When you have a set of constants that logically belong together, the shorthand trick of defining them within a single const block is beneficial.</p><h3>Wrapping up</h3><p>As we wrap up our exploration of Golang’s shorthand tricks, it’s clear that these concise techniques offer more than just brevity.</p><p>They provide a streamlined approach to common coding patterns, enhancing readability and reducing boilerplate. From variable declaration to map initialization, these shorthand methods empower developers to express complex ideas with simplicity.</p><p>So, go ahead, and embrace the elegance of Golang shorthand. Let these tricks be your creative companions for clean and effective code.</p><p>Happy coding and let the knowledge flow! 🚀💻</p><p>P.S. — Don’t hesitate to add a comment if you know any other Golang shorthand tricks!</p><h3>Similar Articles</h3><ul><li><a href="https://blog.canopas.com/golang-utility-functions-you-always-missed-ebeabae6b276">Golang — Utility functions you always missed</a></li><li><a href="https://blog.canopas.com/golang-time-utility-functions-you-will-always-need-d7840d091468">Golang — Time utility functions you will always need</a></li><li><a href="https://blog.canopas.com/golang-firebase-realtime-database-crud-operations-8508e3116887">Golang: Firebase Realtime Database CRUD operations</a></li></ul><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d8d21954c49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/golang-14-shorthand-tricks-you-might-not-know-8d8d21954c49">Golang: 14 Shorthand Tricks You Might Not Know!</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google reCAPTCHA Enterprise: Integrate the “I’m not a robot” Challenge In Vue.js]]></title>
            <link>https://medium.com/canopas/google-recaptcha-enterprise-integrate-the-im-not-a-robot-challenge-in-vue-js-8a83f7d0e374?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a83f7d0e374</guid>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[recaptcha]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 09:55:38 GMT</pubDate>
            <atom:updated>2023-12-04T05:41:32.827Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bat the Bot!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pw3PU9IQh_TkKQKO6JVNNA.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>With the rise of automated bots and malicious activities, it has become crucial for developers to implement robust security measures.</p><p>One such powerful tool that comes to the rescue is the reCAPTCHA integration, which forces the user who accesses an application to verify their identity.</p><p>Google has been defending millions of sites with reCAPTCHA for over a decade. reCAPTCHA Enterprise is built on the existing reCAPTCHA API and it uses advanced risk analysis techniques to distinguish between humans and bots.</p><p>In this blog, we will discuss how to integrate <strong>Google reCAPTCHA Enterprise </strong>with<strong> </strong>your website or web application to protect them against unwanted intrusions.</p><p>Let’s make our web application more secure from ever-persistent <strong>‘bots’</strong>!</p><blockquote>NOTE: we’re not going to use any npm package for recaptcha, instead we will go with the enterprise.js script.</blockquote><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Table Of Contents</h3><pre>* <a href="#7fed">Prerequisites</a><br>* <a href="#3e03">Enable reCAPTCHA Enterprise API</a><br>* <a href="#5972">Create reCAPTCHA Enterprise Key</a><br>* <a href="#a063">Render the checkbox challenge (I&#39;m not a robot)</a><br>  * <a href="#c7a5">Fix grecaptcha is not defined</a><br>* <a href="#13d4">Verify the token using Backend</a></pre><h3>Prerequisites</h3><ul><li>A Google cloud project</li><li>A running vue.js project</li></ul><p>Get ready with the above prerequisites if you’re not already.</p><h3>Enable recaptcha API</h3><p>Navigate to <a href="https://console.cloud.google.com/apis/library/recaptchaenterprise.googleapis.com?"><strong>reCAPTCHA Enterprise</strong></a><strong> </strong>and Enable the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2lmkjdqyQYOLF8us99bYw.gif" /><figcaption>Enable reCAPTCHA Enterprise API</figcaption></figure><p>If you’ve already enabled the API, you will see a screen like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thnLan9Yx1aYbXWVOlfCIw.png" /></figure><p>Consider referring to the <a href="https://cloud.google.com/recaptcha-enterprise/docs/prepare-environment">Google guide</a>, in case you want to know more.</p><h3>Create reCAPTCHA Key</h3><p>To create a reCAPTCHA key, navigate to the <a href="https://console.cloud.google.com/security/recaptcha/create">Create Key tab</a> and Click the <strong>CREATE KEY</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LJQvrEE0qmK2ScjOMneDw.png" /><figcaption>Create a reCAPTCHA site key</figcaption></figure><blockquote>Make sure to enable the <strong>Use tick box challenges</strong> option, it’s can not be modified later.</blockquote><p>You will be able to see the created site key as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaHUkYl8Rhq7VT_uGhHvhA.png" /><figcaption>Creates reCAPTCHA site key</figcaption></figure><p>Refer to more about it at How to create site key for <a href="https://cloud.google.com/recaptcha-enterprise/docs/setup-overview-web">reCAPTCHA Enterprise</a>.</p><h3>Render the checkbox challenge(I’m not a robot)</h3><p>Let’s load the enterprise.js using the mounted hook.</p><p><strong>App.vue</strong></p><pre>&lt;script&gt;<br>export default {<br>  mounted() {<br><br>    let recaptchaScript = document.createElement(&quot;script&quot;);<br>    recaptchaScript.setAttribute(<br>      &quot;src&quot;,<br>      &quot;https://www.google.com/recaptcha/enterprise.js?render=6LdjjyEpAAAAAAXXXXXXXXXXXXXXXXXXXXXXXXO4&quot;<br>    );<br>    recaptchaScript.setAttribute(&quot;async&quot;, &quot;true&quot;);<br>    recaptchaScript.setAttribute(&quot;defer&quot;, &quot;true&quot;);<br>    document.head.appendChild(recaptchaScript);<br>  }<br>}<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;div&gt;reCAPTCHA Enterprise Demo&lt;/div&gt;<br>&lt;/template&gt;</pre><p>When running the application, it shows a bad request error as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhbmdjuFT45NT7y0jcTJmQ.png" /><figcaption>reCAPTCHA render throws a Bad request error</figcaption></figure><blockquote>It’s because we have appended the site key along with the script and that’s not expected for rendering the Checkbox challenge(<a href="https://cloud.google.com/recaptcha-enterprise/docs/instrument-web-pages-with-checkbox">I’m not a robot</a>). However, it’s required for <a href="https://blog.canopas.com/integrate-google-recaptcha-enterprise-using-vue-js-and-golang-60a9335e80ac">Invisible recaptcha integration</a>.</blockquote><p>The script should look like this,</p><pre>recaptchaScript.setAttribute(<br>      &quot;src&quot;,<br>      &quot;https://www.google.com/recaptcha/enterprise.js&quot;<br>    );</pre><p><strong>After removing the site key</strong>, the error is gone. It’s time to render the checkbox challenge now.</p><p>Let’s add the below code inside the mounted hook after the recaptcha enterprise script gets loaded.</p><pre>grecaptcha.enterprise.render(&quot;recaptcha_container&quot;, {<br>        sitekey: &quot;6LdjjyEpAAAAAAXXXXXXXXXXXXXXXXXXXXXXXXO4&quot;,<br>        action: &quot;verify&quot;,<br>        callback: (token) =&gt; {<br>          window.recaptcha_token = token;<br>        },<br> });</pre><p>Add the below &lt;div&gt; inside &lt;template&gt; with an id recaptcha_container , so that grecaptcha can identify it and render the challenge inside it.</p><pre>&lt;div id=&quot;recaptcha_container&quot;&gt;&lt;/div&gt;</pre><p>You will see the browser shows an error like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQaQFYVDU0hN1-esxwaZuw.png" /><figcaption>Error: grecaptcha is not defined</figcaption></figure><blockquote>The error tells us that we want to use grecaptcha instance, but it’s not available yet. It’s because the script is not loaded yet completely.</blockquote><p>The possible workaround is to access the grecaptcha instance only after the recaptcha enterprise script is loaded.</p><blockquote>For that I have tried two solutions, but neither worked.<br><strong>1. Loaded the recaptcha enterprise script synchronously(By removing </strong><strong><em>async</em> keyword)<br>2. Loaded the recaptcha enterprise script inside index.html</strong> — It works on running application without building it, but with build it doesn’t work always — sometime works sometime doesn’t!). <br>So, It’s not the ultimate solution😵, let’s take the bold move toward the right solution🚀.</blockquote><h4>Fix grecaptcha is not defined</h4><ul><li>We’re going to use the kind of promise thing — that’s listening to an <strong>onload </strong>event<strong> </strong>of enterprise.js.</li><li>It will make sure that when we access the grecaptcha instance the script is loaded before always, In case the script is not loaded it will not access the <strong>grecaptcha.enterprise.render()</strong> method anyway!</li></ul><p>Attach an onload event with the recaptcha script and bind it with onloadCallback as below.</p><pre>recaptchaScript.setAttribute(<br>      &quot;src&quot;,<br>      &quot;https://www.google.com/recaptcha/enterprise.js?onload=onloadCallback&quot;<br>    );</pre><p>Now, need to implement <strong>onloadCallback, </strong>which will manage the execution of <strong>grecaptcha.enterprise.render() </strong>method.</p><blockquote><strong>Caution</strong>— If you define <strong>onloadCallback</strong> inside <strong>methods</strong> property of the vue component, the script won’t find it as it loads at the window level whilst the methods are specific to Vue instance and are not accessible globally.</blockquote><p>By considering the above caution, let’s define <strong>onloadCallback </strong>at window level.</p><pre>window.onloadCallback = () =&gt; {<br>       grecaptcha.enterprise.render(&quot;recaptcha_container&quot;, {<br>        sitekey: &quot;6LdjjyEpAAAAAAXXXXXXXXXXXXXXXXXXXXXXXXO4&quot;,<br>        action: &quot;verify&quot;,<br>        callback: (token) =&gt; {<br>          window.recaptcha_token = token;<br>          console.log(&quot;recaptcha token : &quot;, token);<br>        },<br>      });<br>    };</pre><p>Boom!! You will see the reCAPTCHA rendered when you run the application. When you click on the checkbox it will generate a token that you can pass to the backend if you want to verify on the backend side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDkHkLxHA6aVIdkVR8WmOg.gif" /><figcaption>Generate reCAPTCHA</figcaption></figure><h4>Putting it all together…</h4><pre>&lt;script&gt;<br>export default {<br>  mounted() {<br><br>    window.onloadCallback = () =&gt; {<br>       grecaptcha.enterprise.render(&quot;recaptcha_container&quot;, {<br>        sitekey: &quot;6LdjjyEpAAAAAAXXXXXXXXXXXXXXXXXXXXXXXXO4&quot;,<br>        action: &quot;verify&quot;,<br>        callback: (token) =&gt; {<br>          window.recaptcha_token = token;<br>          console.log(&quot;recaptcha token : &quot;, token);<br>        },<br>      });<br>    };<br><br>    let recaptchaScript = document.createElement(&quot;script&quot;);<br>    recaptchaScript.setAttribute(<br>      &quot;src&quot;,<br>      &quot;https://www.google.com/recaptcha/enterprise.js?onload=onloadCallback&quot;<br>    );<br>    recaptchaScript.setAttribute(&quot;async&quot;, &quot;true&quot;);<br>    recaptchaScript.setAttribute(&quot;defer&quot;, &quot;true&quot;);<br>    document.head.appendChild(recaptchaScript);<br>  }<br>}<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;div&gt;reCAPTCHA Enterprise Demo&lt;/div&gt;<br>  &lt;div id=&quot;recaptcha_container&quot;&gt;&lt;/div&gt;<br>&lt;/template&gt;</pre><h3>Verify the token using the Backend</h3><p>To verify the reCAPTCHA token at the backend side, refer to <a href="https://cloud.google.com/recaptcha-enterprise/docs/create-assessment-website"><strong>How to Create Assessments for the Websites</strong></a>.</p><p>Last but not least, if you want to integrate an invisible reCAPTCHA in vue.js, have a look at <a href="https://blog.canopas.com/integrate-google-recaptcha-enterprise-using-vue-js-and-golang-60a9335e80ac">How to integrate Invisible reCAPTCHA</a>.</p><h3>Similar Articles</h3><ul><li><a href="https://blog.canopas.com/integrate-google-recaptcha-enterprise-using-vue-js-and-golang-60a9335e80ac">Integrate Google Recaptcha Enterprise using Vue.js and Golang</a></li><li><a href="https://blog.canopas.com/vue-3-lifecycle-hooks-with-real-time-example-1b772b89e085">Vue 3 lifecycle hooks with real-time example</a></li><li><a href="https://blog.canopas.com/vue-3-component-testing-with-jest-8b80a8a8946b">Vue 3 component testing with Jest</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Also, feedback is most welcome as always, drop them below in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a83f7d0e374" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/google-recaptcha-enterprise-integrate-the-im-not-a-robot-challenge-in-vue-js-8a83f7d0e374">Google reCAPTCHA Enterprise: Integrate the “I’m not a robot” Challenge In Vue.js</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous tasks management made simple: AWS SQS with AWS Lambda]]></title>
            <link>https://medium.com/canopas/asynchronous-tasks-management-made-simple-aws-sqs-with-aws-lambda-32959071c82d?source=rss-2a334125442f------2</link>
            <guid isPermaLink="false">https://medium.com/p/32959071c82d</guid>
            <category><![CDATA[workflow-optimization]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Nidhi D]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 10:30:36 GMT</pubDate>
            <atom:updated>2023-11-20T05:22:46.581Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Optimizing Workflows: AWS SQS and Lambda Collaboration</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtXjyoTANz7R6C9xpjSEiw.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>In the fast-paced realm of modern technology, we often find ourselves dealing with tasks that can’t be done in the blink of an eye.</p><p>Visualize running a popular e-commerce platform where customers place orders or a social media application where users upload and process media files. These tasks take time, and your users won’t wait indefinitely. This is where the magical combination of AWS SQS and Lambda steps in to save the day.</p><p>Let’s have a real-world journey to explore how AWS SQS and Lambda can supercharge your application’s performance! We will implement this collaboration using Golang.</p><h3>Table Of Contents</h3><pre>* <a href="#482e">The Brave Amazon Warriors: AWS SQS and Lambda</a><br>* <a href="#0df1">The Battle Plan: AWS SQS and Lambda in Action</a><br>  * <a href="#8c97">Step 1: Create an SQS Queue</a><br>  * <a href="#aec1">Step 2: Crafting the Lambda Functions(SQS message sender and processor)</a><br>  * <a href="#39d5">Step 3: Battle-Ready Permissions to Lambda function</a><br>  * <a href="#38cb">Step 4: Victory Through Testing</a><br>* <a href="#a453">Benefits of using SQS with AWS Lambda</a><br>* <a href="#4775">Finishing thoughts</a></pre><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>The Brave Amazon Warriors: AWS SQS and Lambda</h3><h4>AWS SQS: Our first hero</h4><p>It’s like <strong>a reliable courier service</strong> that transports messages between different parts of our application. Whether it’s payment processing, order confirmation, or inventory updates, SQS is our messenger. Think of it as a conveyor belt for tasks.</p><h4>AWS Lambda: Our second hero</h4><p>Lambda is like <strong>a team of skilled workers</strong> ready to spring into action. When a message arrives via SQS, Lambda is triggered to execute the necessary code.</p><p>These <strong>workers</strong> can be assigned specific tasks like,</p><ul><li>Processing payments</li><li>Sending emails or</li><li>Updating inventory</li></ul><p>The beauty is that Lambda workers automatically adapt to the workload, like a team of superheroes ready to save the day.</p><h3>The Battle Plan: AWS SQS and Lambda in Action</h3><h4>Step 1: Create an SQS Queue</h4><p>Our first mission is to create an SQS queue to handle incoming messages.<br>The messages will be placed into the SQS queue from any executing program(It can be Lambda, too).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0SrJ3CAmm6r9tG1D.gif" /><figcaption>Create a Queue</figcaption></figure><p>Visit the <a href="https://aws.amazon.com/console/">AWS Management Console</a>, navigate to <a href="https://console.aws.amazon.com/sqs/v3/home"><strong>SQS Service</strong></a>,<strong> </strong>and click on <strong>Create Queue. </strong>If you want to provide SQS access to specific users, modify the access policy accordingly.</p><p>By that, We have our messaging system ready in place.</p><p>P.S. You can choose between <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-queue-types.html">Standard and FIFO queues</a> as per the requirement.</p><h4>Step 2: Crafting the Lambda Functions(SQS message sender and processor)</h4><p>Our Lambda functions are like specialized blacksmiths who craft different components of our e-commerce machinery.</p><p>Here, we will create two Lambda functions. One is to place a message in a Queue and another is to process a message from Queue.</p><p>Let’s create our message sender Lambda function first.</p><ul><li><strong>Create a Lambda function “AddMessageToQueue” to add a message in the SQS Queue</strong></li></ul><p>In the <a href="https://aws.amazon.com/console/">AWS Management Console</a>, navigate to the <a href="https://console.aws.amazon.com/lambda/home">AWS Lambda service</a>, and click <strong>Create Function</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mMgkonxLpkPo3T9e.gif" /><figcaption>Create a Lambda function that adds a message to the SQS Queue</figcaption></figure><p>P.S. — We have chosen <strong>Go 1.x</strong> as an environment for our Lambda function, feel free to opt for the environment of your choice!</p><ul><li><strong>Add Code to the Lambda function and point out the Lambda handler</strong></li></ul><p><strong>sqs_message_sender/main.go</strong></p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;strconv&quot;<br><br> &quot;github.com/aws/aws-lambda-go/lambda&quot;<br> &quot;github.com/aws/aws-sdk-go/aws&quot;<br> &quot;github.com/aws/aws-sdk-go/aws/credentials&quot;<br> &quot;github.com/aws/aws-sdk-go/aws/session&quot;<br> &quot;github.com/aws/aws-sdk-go/service/sqs&quot;<br>)<br><br>const (<br> AWS_ACCESS_KEY_ID     = &quot;AKXXXXXXXXXXXXXXXXXX&quot;<br> AWS_SECRET_ACCESS_KEY = &quot;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;<br> AWS_REGION            = &quot;us-east-1&quot;<br> AWS_SQS_URL           = &quot;https://sqs.us-east-1.amazonaws.com/XXXXXXXXXXXX/sample.fifo&quot;<br>)<br><br>func Handler(ctx context.Context) (string, error) {<br> fmt.Println(&quot;I&#39;m going to push a message to the SQS queue&quot;)<br><br> // SQS message-sending logic goes here<br> AddMessageToQueue(1, 2)<br><br> return &quot;Message sent successfully&quot;, nil<br>}<br><br>func main() {<br> lambda.Start(Handler)<br>}<br><br>func AddMessageToQueue(productId, quantity int) {<br> awsSession, err := GetAWSSession()<br> if err != nil {<br>  panic(err)<br> }<br><br> // prepare SQS client<br> sqsClient := sqs.New(awsSession)<br><br> // prepare message attributes to push into queue<br> messageAttributes := map[string]*sqs.MessageAttributeValue{<br>  &quot;ProductId&quot;: {<br>   DataType:    aws.String(&quot;String&quot;),<br>   StringValue: aws.String(strconv.Itoa(productId)),<br>  },<br>  &quot;Quantity&quot;: {<br>   DataType:    aws.String(&quot;String&quot;),<br>   StringValue: aws.String(strconv.Itoa(quantity)),<br>  },<br> }<br><br> // send message to the queue<br> _, err = sqsClient.SendMessage(&amp;sqs.SendMessageInput{<br>  MessageGroupId:         aws.String(&quot;productId&quot; + fmt.Sprint(productId)),<br>  MessageDeduplicationId: aws.String(&quot;productId&quot; + fmt.Sprint(productId) + &quot;_&quot; + fmt.Sprint(quantity)),<br>  MessageAttributes:      messageAttributes,<br>  MessageBody:            aws.String(&quot;Going to process queue for item : &quot; + fmt.Sprint(productId)),<br>  QueueUrl:               aws.String(AWS_SQS_URL),<br> })<br><br> if err != nil {<br>  panic(err)<br> }<br>}<br><br>func GetAWSSession() (*session.Session, error) {<br> fmt.Println(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)<br> credential := credentials.NewStaticCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, &quot;&quot;)<br><br> _, err := credential.Get() /* get AWS credentials */<br> if err != nil {<br>  return nil, err<br> }<br><br> cfg := aws.NewConfig().WithRegion(AWS_REGION).WithCredentials(credential) /* configure AWS account with credentials and region */<br><br> session, err := session.NewSession(cfg)<br><br> if err != nil {<br>  return nil, err<br> }<br><br> return session, nil<br>}</pre><p>Create a zip of the binary of the above file and upload it as a code for the Lambda function.</p><blockquote>Create a binary<em> — </em><strong><em>GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main main.go</em></strong></blockquote><blockquote>Create a zip file<em> — </em><strong><em>zip main.zip main</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zf-LBqAxhwavnUO6.gif" /><figcaption>Add Code and point out the lambda handler</figcaption></figure><ul><li><strong>Test the Lambda function by adding a message to the SQS Queue</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XytZrr8kVGiijRhO.gif" /><figcaption>Verify adding a message to the Queue from a Lambda function</figcaption></figure><p>Let’s move toward creating the SQS message processor Lambda.</p><ul><li><strong>Create a Lambda function “ProcessQueueMessage”<br></strong>This function will be responsible for receiving messages from the SQS queue and will proceed further.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dw918wjtDxeKXyK5.gif" /><figcaption>Create a Lambda function to process a Queue message</figcaption></figure><ul><li><strong>Add code to the Lambda function and point out the lambda handler</strong></li></ul><p><strong>sqs_message_processor/main.go</strong></p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br><br> &quot;github.com/aws/aws-lambda-go/events&quot;<br> &quot;github.com/aws/aws-lambda-go/lambda&quot;<br>)<br><br>func main() {<br> lambda.Start(ListenAndProcessSQSMessage)<br>}<br><br>// listens event from SQS(whenver any new message is placed in SQS Queue)<br>func ListenAndProcessSQSMessage(c context.Context, sqsEvent events.SQSEvent) {<br> fmt.Println(&quot;Lambda is triggered by SQS&quot;)<br><br> fmt.Println(&quot;sqsEvent : &quot;, sqsEvent)<br><br> data := make(map[string]interface{})<br><br> for _, item := range sqsEvent.Records {<br>  for k, v := range item.MessageAttributes {<br>   data[k] = *v.StringValue<br>  }<br> }<br><br> fmt.Println(&quot;data : &quot;, data) // map[ProductId:1 Quantity:2]<br>}</pre><p>Again, create a binary of the above file, generate a zip of it, and upload it to the Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p-hk8bYbaYgA8J0F.gif" /><figcaption>Point out the lambda handler for the ProcessQueueMessage function</figcaption></figure><blockquote>Make sure you create a separate project for deploying the <strong>ProcessQueueMessage</strong> Lambda, because of two reasons:</blockquote><blockquote>1. Lambda uses the executable file name, for pointing out the lambda handler(<strong>main.go</strong> in our case) -&gt; that we have already used for <strong>AddMessageToQueue</strong> Lambda function</blockquote><blockquote>2. For <strong>ProcessQueueMessage, </strong>in<strong> </strong>case of adding the lambda handler code into other file than of main.go, for example hello.go. It will be unable to find out the handler unless we add it inside <strong>main()</strong>. But inside a package <strong>main there can only be one main() method as per Go’s nature.</strong></blockquote><blockquote>Therefore, it’s not possible for Golang in straight forward way, it’s possible for other languages though.<br>Refer: <a href="https://github.com/aws/aws-lambda-go/issues/182">https://github.com/aws/aws-lambda-go/issues/182</a></blockquote><p>Now, the Lambda function can be assigned a specific task, like processing payments, sending order confirmations, or updating inventory. Which is automatically executed when a message arrives in the SQS queue.</p><h4>Step 3: Battle-Ready Permissions to Lambda function</h4><p>It’s time to ask our brave soldiers to access the tool as per the requirements on the battlefield.</p><p>Whoa! I’m talking about pointing out our message processor Lambda function(ProcessQueueMessage) to tackle the order from the SQS Queue, whenever the Queue receives any message from the message sender Lambda function(AddMessageToQueue).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwUS5XHGYL8ziwAHA_TmRg.gif" /><figcaption>Add Lambda trigger to SQS Queue</figcaption></figure><blockquote>The error above shows that the lambda role is lacking permission to access SQS Service.<br>We need to make sure our Lambda functions have the right permissions to access the SQS queue. This is like equipping our blacksmiths with the right tools for the job.</blockquote><p>Let’s now add the required permissions to the Lambda function role so that Lambda can easily access the SQS service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUx6kUd8O0BLBXEfQq9e0Q.gif" /><figcaption>Add SQS access policy to the lambda execution role</figcaption></figure><p>Permission is all set. It’s time to add the lambda trigger to the SQS Queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tx4GSaCNyiIgdh1GuJplag.gif" /><figcaption>Add Lambda trigger to SQS Queue</figcaption></figure><p>Yayy! It worked.</p><h4>Step 4: Victory Through Testing</h4><p>With everything set up, we test our system to ensure it’s battle-ready. It’s like watching our army in training to defend our kingdom.</p><p>We send a test message to the SQS queue and observe our Lambda functions swing into action.</p><p>Let’s run <strong>AddMessageToQueue </strong>which will place the message to Queue and Queue will trigger the <strong>ProcessQueueMessage </strong>Lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*liALrEyZqDLxh6Ecsw1hfA.gif" /><figcaption>Place message to SQS queue</figcaption></figure><p>Check Cloudwatch logs by navigating to the <a href="https://console.aws.amazon.com/cloudwatch">Cloudwatch</a> service. You will see the logs as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeIWJztxL0pduL1KGeGkrA.png" /><figcaption>SQS queue has triggered the Lambda function <strong>ProcessQueueMessage</strong></figcaption></figure><p><strong>AddMessageToQueue </strong>has placed our message with ProductId and Quantity to the SQS queue and the queue has passed it to the lambda function <strong>ProcessQueueMessage.</strong></p><p>We can further process the passed message data from <strong>ProcessQueueMessage</strong>. For example to update the inventory in our case.</p><p>Congratulations!🎉, You have just learned a trick to optimize your project architecture by moving asynchronous operations to SQS.</p><h3>Benefits of using SQS with AWS Lambda</h3><p>As we journey through this process, we experience several real-world benefits.</p><h4>1. Scalability</h4><p>Just like during a massive shopping festival, our system can handle a surge in orders without breaking a sweat. We can dynamically adjust the number of SQS queues and Lambda functions to match our application’s needs.</p><h4>2. Reliability</h4><p>Messages in SQS are stored redundantly, and Lambda is a reliable, serverless service that takes care of error recovery and scaling. Our customers can trust that their orders will be processed without a hitch.</p><h4>3. Simplified Architecture</h4><p>We can focus on our core business because we don’t need to worry about server management and message queue maintenance. AWS handles these operational tasks, simplifying our architecture.</p><h4>4. Cost Optimization</h4><p>We’ve optimized our costs by configuring our resources efficiently while meeting our application’s demands. P.S. AWS Lambda works on the principle <strong>Pay as you go, </strong>that too as per the execution duration<strong>.</strong></p><h3>Finishing thoughts</h3><p>Background processing is an essential part of almost every development we do. It’s better to optimize the execution flow by separating the instant and time-consuming tasks to provide a delightful user experience.</p><p>So, whether you’re…</p><ul><li>Building a popular e-commerce website or</li><li>Processing user-generated content on a social media platform or</li><li>Managing any task that benefits from background processing or</li><li>Building your favorite game application to reward users based on their scores</li></ul><p>Consider the dynamic duo of <strong>AWS SQS and Lambda</strong> to simplify your architecture and supercharge your asynchronous task management.</p><p>This isn’t just a tech solution, it’s a real-world game-changer! You can adapt this collaboration for any of the cloud providers or any programming language you find flexible to use.</p><h3>Similar Articles</h3><ul><li><a href="https://blog.canopas.com/golang-serverless-deployment-using-aws-cloudformation-4dee745cbf28">Golang: Serverless deployment using AWS Cloudformation</a></li><li><a href="https://blog.canopas.com/golang-serverless-microservices-with-gin-f3c2a4943a6d">Golang: Serverless Microservices with gin</a></li><li><a href="https://blog.canopas.com/deploy-a-website-with-aws-s3-cloudfront-using-cloudformation-c2199dc6c435">Deploy a website with AWS S3 + CloudFront using CloudFormation</a></li></ul><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32959071c82d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/asynchronous-tasks-management-made-simple-aws-sqs-with-aws-lambda-32959071c82d">Asynchronous tasks management made simple: AWS SQS with AWS Lambda</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>