<?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 Santosh Kumar on Medium]]></title>
        <description><![CDATA[Stories by Santosh Kumar on Medium]]></description>
        <link>https://medium.com/@sntshk?source=rss-cf8f28329b2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Uc-aJnZEDaxyfJPh.jpg</url>
            <title>Stories by Santosh Kumar on Medium</title>
            <link>https://medium.com/@sntshk?source=rss-cf8f28329b2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:47:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sntshk/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[__str__ vs __repr__ in Python and When to Use Them]]></title>
            <link>https://sntshk.medium.com/str-vs-repr-in-python-and-when-to-use-them-57b5a231d3f6?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/57b5a231d3f6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[syntax]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 07:01:35 GMT</pubDate>
            <atom:updated>2023-02-25T05:36:35.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*21jYWpGEIHOqkGDy.png" /></figure><h3>Introduction</h3><p>In a previous post, we have done a comparison between __new__ and __init__. In this post, we are going to do something similar, but with a different pair.</p><p>For those who don’t know, __str__() and __repr__() are two dunder methods which you can override in a class to change the way class is represented.</p><p>These two little functions have been a source of confusion in my early career. Let us first go through them one by one and let us understand what they do first. Then we’ll do comparison among them with respect to their similarities and differences.</p><h3>__str__() and str()</h3><p>If you have worked with other language before coming to Python, you might be familiar with str() or string() function, which would cast any other data type to String data type or class.</p><p>Python behaves the same. Here is an example in Python REPL.</p><pre>&gt;&gt;&gt; my_int = 2<br>&gt;&gt;&gt; type(my_int)<br>&lt;class &#39;int&#39;&gt;<br>&gt;&gt;&gt; my_str = str(my_int)<br>&gt;&gt;&gt; type(my_str)<br>&lt;class &#39;str&#39;&gt;</pre><p>Simlar is the repr() function. repr also returns a string.</p><pre>&gt;&gt;&gt; my_int = 2<br>&gt;&gt;&gt; type(my_int)<br>&lt;class &#39;int&#39;&gt;<br>&gt;&gt;&gt; my_repr = repr(my_int)<br>&gt;&gt;&gt; type(my_repr)<br>&lt;class &#39;str&#39;&gt;</pre><h3>__repr__() and repr()</h3><p>By now you understand that both the dunder method has their corresponding function symbols in which you can pass another data type.<br> We also saw in the previous section that when you pass anything to repr(), it simply turns into a str data type.</p><h3>__str__() and __repr__() in a Class</h3><p>If you still don’t know about dunder methods, this section might help you understand it.</p><p>There is a <a href="https://www.reddit.com/r/Python/comments/br9ok2/list_of_all_python_dunder_methods/">massive list of Python dunder methods</a>. Dunder methods allow the way your handwritten class to behave in a certain manner.</p><p>The difference between the two methods is that __str__ is intended to provide a human-readable representation of the object, while __repr__ should provide a representation that can be used to recreate the object.</p><p>Let’s see the difference between the two with the help of a simple code example:</p><pre>class Point:<br>    def __init__(self, x, y):<br>        self.x = x<br>        self.y = y<br><br>    def __str__(self):<br>        return f&quot;({self.x}, {self.y})&quot;<br><br>    def __repr__(self):<br>        return f&quot;Point({self.x}, {self.y})&quot;<br><br>p = Point(1, 2)<br><br>print(p) # Output: (1, 2)<br>print(repr(p)) # Output: Point(1, 2)</pre><p>In the example above, __str__ returns a string representation of the Point object that is intended to be human-readable. The __repr__ method returns a string representation that could be used to recreate the object.</p><p>In general, it is recommended to always define a __repr__ method for your objects, so that you have an unambiguous representation of the object that can be used for debugging or in a REPL environment. On the other hand, __str__ is typically only defined when a more human-readable representation is needed. If __str__ is not defined for an object, repr(obj) is used as a fallback.</p><p>It’s worth noting that the __str__ method should return a string, while the __repr__ method should return a string that, when passed to the eval() function, returns an object with the same value. The recommended format for __repr__ is a string that, when passed to eval(), creates an object with the same value as the original. In the example above, the Point object can be recreated by calling Point(1, 2).</p><h3>Conclusion</h3><p>In conclusion, __str__ and __repr__ are two important methods in Python that allow you to define string representations of objects. Understanding the difference between the two and when to use them is important in creating robust and well-designed code.</p><p><strong>Keep reading</strong>:</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2023/__str__-vs-__repr__-and-when-to-use-them/"><em>https://santoshk.dev</em></a><em> on February 11, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57b5a231d3f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Control Philips Wiz Bulb Using Go]]></title>
            <link>https://sntshk.medium.com/how-to-control-philips-wiz-bulb-using-go-476d58425b88?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/476d58425b88</guid>
            <category><![CDATA[philips-hue]]></category>
            <category><![CDATA[philips-wiz]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[home-automation]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 15:09:09 GMT</pubDate>
            <atom:updated>2023-02-18T17:02:41.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j_pWyI6ojWqDDa7Y.jpg" /></figure><h3>Introduction</h3><p>I have always been conscious about privacy and it was the sole reason I wasn’t early adapter of smart home devices. This changed when I bought Raspberry Pi. I learned that I can make my Pi hub to all the smart devices at my home.</p><p>And this is how I bought 9W Philips Wiz light; the cheapest one I could get in the Indian market.</p><p>To use this product, you at least need to have a home network (a wifi router will work). The router does not need to have internet connection.</p><h3>Control Philips Wiz using App</h3><p>The most common way to control the Wiz light is using the mobile app. It is available for both <a href="https://play.google.com/store/apps/details?id=com.tao.wiz&amp;hl=en_IN&amp;gl=US&amp;pli=1">Android</a> and <a href="https://apps.apple.com/us/app/wiz-connected/id1497247770">iOS</a>.</p><p>I don’t want to cover how to operate the bulb using the app. I would leave it upto you. I want you to explore the app completely before proceeding towards the next section.</p><p>As we are going to control the bulb using code, I want you to practice doing these actions:</p><ul><li>Turn on/off</li><li>Set colors</li><li>Set brightness</li><li>Set temperature</li><li>Set modes</li></ul><h3>Control Philips Wiz using Go</h3><p>While there are libraries available to interact with the bulb, I wanted to show you guys what happens internally with the bulb. In a home automation scenario, you’d mostly be using such libraries.</p><h3>Find the bulb IP</h3><p>Before we write any piece of code, it is crucial to find out the IP of your bulb. In most latest routers, they show what clients are connected to the router, the device name should appear as wiz_xxxxxx where xxxxxx is the starting mac address of the bulb.</p><p>If somehow your router does not supports showing the IP of connected devices, you’ll have to do some hit and trial.</p><ul><li>Get the IP of your PC/Laptop. You can run ip a if you are on Linux. My PC&#39;s IP is 192.168.0.100.</li><li>Turn off the light from the app and send the <em>Hello Philips Wiz</em> code described in next section to each of the IPs near to your PCs IP.</li></ul><p>So I’d send following message to 192.168.0.95–105. How many machines you have to try depends on how many devices you have on your network.</p><p>We need the IP because we are going to communicate with bulb by sending and receiving UDP messages.</p><h3>Hello Philips Wiz using UDP</h3><pre>package main<br><br>import &quot;net&quot;<br><br>var wizIP = &quot;192.168.0.101&quot;  // this is address on my bulb in my network<br>const wizPort = &quot;38899&quot;<br><br>func main() {<br> c, err := net.Dial(&quot;udp&quot;, fmt.Sprintf(&quot;%s:%s&quot;, wizIp, wizPort)<br> if err != nil {<br>  panic(&quot;could not connect to wiz light&quot;)<br> }<br><br> c.Write([]byte(`{&quot;method&quot;: &quot;setPilot&quot;, &quot;params&quot;:{&quot;state&quot;: true}}`))<br>}</pre><p>Starting at line 5, first we have to define the IP of the bulb. It is 192.168.0.101 in my case.</p><p>Next we have to define the port on which Wiz light listens on. This port ID is constant and won’t change unlike the wizIP.</p><p>Line 14 is the most important. The message is actually a JSON. Let’s beautify it before discussing about it.</p><pre>{<br>  &quot;method&quot;: &quot;setPilot&quot;,<br>  &quot;params&quot;: {<br>    &quot;state&quot;: true<br>  }<br>}</pre><ol><li>“method”: The first key in the JSON object is method. This is either getPilot or setPilot depending on whether you want to get the state of the bulb, or set a state to the bulb. In our case, we are going to set some state. I have never really used the getPilot method, yet.</li><li>“params”: Next in the JSON object is parameters we are sending; it is denoted by params in the JSON body. This is going to complement the method.</li></ol><p>Now depending on what we are trying to do with the bulb, the params are going to change. In above code, we are just saying to set the state to true, which literally means to start the bulb.</p><p>If your bulb was off, it would have turned on after running the above code.</p><p>Similarly, if you want to turn it off, change the state to false and send the message again.</p><h3>Set custom colors</h3><p>Wiz accepts RGB colors values. If you don’t know what that means, go to google and type in “rgb color picker”, then choose a color and then note the RGB value. For example, value for pure <strong>red</strong> would be 255, 0, 0. Here 255 is the value of red, and 0 is for both green and blue.</p><p>To set Wiz to red color, this message can be sent:</p><pre>{<br>  &quot;method&quot;: &quot;setPilot&quot;,<br>  &quot;params&quot;: {<br>    &quot;r&quot;: 255,<br>    &quot;g&quot;: 0,<br>    &quot;b&quot;: 0<br>  }<br>}</pre><p>You have already seen how to send that message.</p><h3>Set brightness</h3><p>In the app UI, you must have seen the brightness slider? If not, consider the following screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NxzyW7Q2VOtml1iB.jpg" /><figcaption>App showing temperature and brightness slider</figcaption></figure><p>First of all, I have warm white light selected. The top slider is for temperature, which we are going to talk about in next section.</p><p>The lowest value for brightness is 10, and max is 100. You guessed it right, lowest is not 0 because at 0, the bulb will be off.</p><p>You can club brightness setting with scene settings as well as any color setting. In following message, I’m setting the color to green and brightness to 50%.</p><pre>{<br>  &quot;method&quot;: &quot;setPilot&quot;,<br>  &quot;params&quot;: {<br>    &quot;r&quot;: 255,<br>    &quot;g&quot;: 0,<br>    &quot;b&quot;: 0,<br>    &quot;dimming&quot;: 50,<br>  }<br>}</pre><h3>Set temperature</h3><p>Setting temperature is similarly easy. There is a params called temp. The range is between 2200 to 6200.</p><p>To the best of my knowledge, temperature can only be clubbed with brightness.</p><p>Here I’m presenting you an example payload for the message demonstrating 2200 kelvin temperate with a intensity of 20%.</p><pre>{<br>  &quot;method&quot;: &quot;setPilot&quot;,<br>  &quot;params&quot;: {<br>    &quot;temp&quot;: 2200<br>    &quot;dimming&quot;: 20,<br>  }<br>}</pre><h3>Conclusion</h3><p>When I bought my Philips Wiz, I had no intention of controlling it programatically. It would such an overkill.</p><p>But shortly after this buy, I also <a href="https://santoshk.dev/posts/2023/first-month-with-my-raspberry-pi/">bought a Raspberry Pi</a>. I became aware that this programatic access can be integrated by home automation.</p><p>Libraries already exist in Python. One of them is <a href="https://github.com/sbidy/pywizlight">pywizlight</a>, which seems to be most mature. But there are many more.</p><p>Maybe we could write some similar library in Go.</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2023/how-to-control-philips-whiz-bulb-using-go/"><em>https://santoshk.dev</em></a><em> on January 25, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=476d58425b88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First Month With My Raspberry Pi]]></title>
            <link>https://sntshk.medium.com/first-month-with-my-raspberry-pi-5fd3e61b0aa0?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd3e61b0aa0</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[home-automation]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 10:34:29 GMT</pubDate>
            <atom:updated>2023-02-17T05:51:17.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0nZDmwjQFkOFGIBP.jpg" /></figure><h3>Introduction</h3><p>It’s no longer than a month since I bought a Raspberry Pi. Pi 4B to be precise. In this post, I’m going to log how I spent my 1st month with it.</p><h3>Setup the Pi</h3><p>When I decided to buy Raspi, I decided not to go with the kit. The reason was the model I was looking for, which is <em>8GB Model B</em> wasn’t available in India. And finding a kit for it would have been more challenging.</p><p>So I bought the Pi itself from <a href="https://www.olelectronics.in/product/raspberry-pi-4-8gb-model-b/"><strong>OL Electronics</strong></a>. It cost me <strong>₹10,700</strong> INR with taxes and delivery charge.</p><p>As you might know, Pi does not ship with a power adapter. So I bought one from <a href="https://robu.in/product/orange-power-supply-adapter-charger-5v-3a-c-type/">robu.in</a>. It cost me <strong>₹315</strong> with delivery charges.</p><p>Pi also does not come with a memory card. I tried searching for 64 micro sd cards offline and online. The best deal was from Amazon. It cost me <strong>₹539</strong>. You will also need a card reader, which I bought from the local market at a price of <strong>₹30</strong>.</p><p>While flashing, I choose to use the Lite variant of OS which comes without a desktop environment and has a footprint of 300 MB on disk.</p><h3>Setting up the OS</h3><p>The Pi board, a 5V 3A Type-C power adapter, a micro sd, and a card reader is all you need to boot up a Pi. You don’t need a monitor or HDMI adapter if you already have a laptop because you can also SSH to your Pi to do your work remotely and that is how I usually work on my Pi.</p><p>As you know, I use Ubuntu on my machine. If you are also using Ubuntu, you can install it by:</p><pre>sudo apt install rpi-imager</pre><p>Instruction for other operating systems can be found on <a href="https://github.com/raspberrypi/rpi-imager">their GitHub page</a>.</p><p>Put a micro sd card in the card reader and Please consider watching <a href="https://www.youtube.com/watch?v=ntaXWS8Lk34">How to use Raspberry Pi Imager</a>.</p><h3>Blink Light</h3><p>I prefer to use the gpiozero package for dealing with GPIO. But there is also an RPi module.</p><pre>import time<br>from gpiozero import LED<br><br>led = LED(18)<br><br>while True:<br>    led.on()<br>    time.sleep(1)<br>    led.off()<br>    time.sleep(1)</pre><p>Make sure you attach the long head of the LED to pin 18.</p><p>There is also an equivalent code using the RPi package:</p><pre>import time<br>import RPi.GPIO as GPIO<br><br>led_pin = 18<br>GPIO.setmode(GPIO.BCM)<br>GPIO.setup(led_pin, GPIO.OUT)<br><br>while True:<br>    GPIO.output(led_pin, True)<br>    time.sleep(1)<br>    GPIO.output(led_pin, False)<br>    time.sleep(1)</pre><p>I have also short a video I have <a href="https://instagram.com/fullstackwithsantosh">posted on Instagram</a>. Here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*-9vLKZcnjjJuPkvM.gif" /><figcaption>Blinking LED using GPIO programming</figcaption></figure><h3>Actuate on Proximity</h3><p>Here I have used both packages to run something when the proximity sensor detects any object near the sensor.</p><p>The sensor I am using is an IR proximity sensor.</p><pre>import time<br><br>from gpiozero import LED<br>import RPi.GPIO as GPIO<br><br>GPIO.setmode(GPIO.BOARD)<br>GPIO.setup(8, GPIO.IN)<br><br>led = LED(18)<br><br>while True:<br>    if GPIO.input(8) == 0:<br>        print(&quot;turning light on&quot;)<br>        led.on()<br>    else:<br>        print(&quot;turning light off&quot;)<br>        led.off()<br><br>    time.sleep(0.1)</pre><p>Here is what it does:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*V7Id-YQSqrGEDD8J.gif" /><figcaption>IR sensor in action</figcaption></figure><h3>Controlling LED brightness, 0–100 and back</h3><p>Below is Python code to change the brightness of a LED light using Raspberry Pi.</p><pre>import time<br>import RPi.GPIO as GPIO<br><br>led_pin = 18<br>GPIO.setmode(GPIO.BCM)<br>GPIO.setup(led_pin, GPIO.OUT)<br><br>pwm_led = GPIO.PWM(led_pin, 500)<br>pwm_led.start(100)<br><br>while True:<br>    start = 0<br>    end = 100<br>    while start &lt; end:<br>        pwm_led.ChangeDutyCycle(start)<br>        time.sleep(.025)<br>        start += 1<br>    break</pre><p>I don’t shoot a video for this one because the intensity was so low that it was very hard to distinguish between different strengths of light.</p><h3>Controlling an RGB light (failed)</h3><p>I have also bought a common cathode LED. But somehow, I’m not able to turn on the LED. Not sure if the problem is in the LED, my code, or the pins.</p><p>Here is the code I was using.</p><pre>from gpiozero import RGBLED<br><br>led = RGBLED(22, 27, 17)<br><br>led.color = (1, 0, 0)</pre><p>And here is the setup I was using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8QL7OyQGUCSUiPmF.jpg" /><figcaption>Failed attempt to use RGB LED</figcaption></figure><p>In the above image, the blue, green, and red are placed at 6, 7, and 8 on the left column, and the common cathode is placed at 3rd from the right.</p><p>Please let me know if you have a solution for this one.</p><h3>Conclusion</h3><p>This is not the entirety of the things I have done with my Raspberry Pi in the first month. I have a DHT11 sensor which I mistakenly bought without the IC. And now I need a 4.7K resistor to work with it. I am yet to order the resistor.</p><p>Alongside Raspi accessories, I have also bought some NFC tags to play with. I will post another blog if I make something interesting with it.</p><p>Installing Home Assistant is another thing that I have done on my Pi. This board is going to be the hub of other smart devices on my network. I’m planning to buy some ESF32 to help me with my home automation journey.</p><p>If you are also keen on home automation and IoT, I’d recommend you <a href="https://github.com/microsoft/IoT-For-Beginners">IoT for Beginners</a>.</p><p>Let me know if you want more articles like this one.</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2023/first-month-with-my-raspberry-pi/"><em>https://santoshk.dev</em></a><em> on January 3, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd3e61b0aa0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Classes in Golang]]></title>
            <link>https://sntshk.medium.com/how-to-write-classes-in-golang-1446e06245a7?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1446e06245a7</guid>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 09:51:22 GMT</pubDate>
            <atom:updated>2023-02-16T15:02:44.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NJEPg5oJq4cwRtz2.jpg" /></figure><h3>Introduction</h3><p>I have seen many people coming from Python background struggling with Go. What I have obeserved it they write code that is limited to writing functions and calling them. They never leverage design constructs such as abstraction, encapsulation, inheritance, composition etc. I can understand their pain because I’ve been in the same boat.</p><p>In today’s post I’ll compare how we write classes in Python vs how we do the same thing in a Go way.</p><h3>What is a class composed of?</h3><ol><li>Attributes in form of variables</li><li>Behavior in form of methods</li></ol><h3>Example in Python</h3><p>Consider the following code in Python that defines a simple Person class with a name attribute and a greet method:</p><pre>class Person:<br>    def __init__(self, name):<br>        self.name = name<br>    <br>    def greet(self):<br>        print(f&quot;Hello, my name is {self.name}&quot;)<br><br>p = Person(&quot;John&quot;)<br>p.greet()  # prints &quot;Hello, my name is John&quot;</pre><p>If you’re a Python programmer looking to learn Go, you’ll be happy to know that Go has a similar concept to classes called “structs”. Structs are similar to classes in that they allow you to define a custom data type with its own fields and methods.</p><h3>Struct to define the structure and attributes</h3><p>To define a struct in Go, you use the type keyword followed by the name of the struct and a set of curly braces containing the fields. Here’s an example of a simple struct called Person:</p><pre>type Person struct {<br>    name string<br>    age  int<br>}</pre><p>This defines a struct called Person with two fields: name and age, both of which are of type string and int respectively.</p><h3>Method or behaviour using receiver function</h3><p>You can also define methods on your structs by using the func keyword and attaching the method to the struct using the (p *Person) syntax, where p is the receiver of the method and Person is the type of the receiver. Here’s an example of a method called SayHello that prints a greeting to the console:</p><pre>func (p *Person) SayHello() {<br>    fmt.Printf(&quot;Hello, my name is %s and I am %d years old\n&quot;, p.name, p.age)<br>}</pre><p>To create an instance of a struct, you can use the new function or the shorthand syntax :=. Here’s an example of both:</p><pre>// Using the new function<br>p1 := new(Person)<br>p1.name = &quot;John&quot;<br>p1.age = 30<br><br>// Using the shorthand syntax<br>p2 := Person{name: &quot;Jane&quot;, age: 25}</pre><p>You can also define a “constructor” function to create instances of your struct. This can be useful if you want to perform some initialization logic when creating a new instance. Here’s an example of a constructor function for the Person struct:</p><pre>func NewPerson(name string, age int) *Person {<br>    p := new(Person)<br>    p.name = name<br>    p.age = age<br>    return p<br>}</pre><p>You can then use this constructor function to create a new instance of the Person struct like this:</p><pre>p := NewPerson(&quot;Bob&quot;, 35)</pre><p>I hope this tutorial has helped you understand how to define and use structs in Go as a Python programmer. Structs are a powerful and flexible way to define custom data types in Go, and I encourage you to explore them further.</p><p>Thank you for reading!</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2022/how-to-write-classes-in-golang/"><em>https://santoshk.dev</em></a><em> on December 20, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1446e06245a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing HTTP Requests with Postman]]></title>
            <link>https://sntshk.medium.com/testing-http-requests-with-postman-209957d27849?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/209957d27849</guid>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[api-testing]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Thu, 08 Dec 2022 09:14:14 GMT</pubDate>
            <atom:updated>2023-02-15T07:16:41.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*O7grYWsYqJAvRzBJ.jpg" /></figure><h3>Introduction</h3><p>In <a href="https://santoshk.dev/posts/2022/postman-premier-the-minimal-postman-you-need-to-learn/">Postman Premier — The Minimal Postman you need to Learn</a>, I posted the minimum of Postman you need to learn. In this article, I’m going to expand on that knowledge and dig more into the response. In this post, I’ll be asserting the response on certain values and response codes and more.</p><h3>What are assertions and how to use it</h3><p>Assertions are nothing but test cases we give to a particular request. In the previous post, we already have seen that each of the requests has a <strong>Tests</strong> tab. There we write code in JavaScript, judging specific parameters of the response.</p><p>Let’s first test for a specific status code. Just for context, while testing, I’m going to use my gingo server.</p><h3>Looking for a specific status code</h3><p>Testing for a specific status code is one of the easiest tasks to do within Postman. I’m going to use my GET {{baseUrl}}/books endpoint for this purpose.</p><p>When you open the <strong>Tests</strong> tab, you’ll see snippets on the right side column. Click on <strong>Status code: Code is 200</strong>.</p><p>The code area will be populated with the following:</p><pre>pm.test(&quot;Status code is 200&quot;, function () {<br>    pm.response.to.have.status(200);<br>});</pre><p>When you send the request, you’ll see <strong>Test Results (1/1)</strong> under the response section. That area shows how many of your tests have passed or failed.</p><p>I’ve recorded a gif for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*_3QNEHPbnPzEuRKj.gif" /><figcaption>Testing for specific status code</figcaption></figure><p>This was for the positive assertions, you can send wrong data and do a negative assertion as well.</p><h3>Looking for a specific string in the body</h3><p>For this test, I’ll be using the GET {{baseUrl}}/books/:isbn endpoint, with isbn&#39;s value to be 9781612680194.</p><p>Looking for a specific string in the body is not much different from checking for a status code. You’ll find a snippet for it as well. Snippets are a great way to explore assertion in Postman.</p><p>Look for an assertion called <strong>Response body: Contains string</strong>. It will spit this source code into the test panel.</p><pre>pm.test(&quot;Body matches string&quot;, function () {<br>    pm.expect(pm.response.text()).to.include(&quot;string_you_want_to_search&quot;);<br>});</pre><p>I’m going to modify the body:</p><pre>pm.test(&quot;Body includes Rich Dad Poor Dad&quot;, function () {<br>    pm.expect(pm.response.text()).to.include(&quot;Rich Dad Poor Dad&quot;);<br>});</pre><p>Now I’m not going to include a gif for this as this would be very identical to the previous one.</p><h3>Looking for a specific header</h3><p>Another thing we can test in a REST API is headers. Some use cases to look for a header are:</p><ol><li>When you are expecting a specific content type</li><li>When you are expecting an authentication token as a response to a request.</li></ol><p>For a header, the testing code would look like this:</p><pre>pm.test(&quot;Content-Type is application/json&quot;, function () {<br>    pm.response.to.have.header(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>});</pre><h3>Adding tests at the collection level</h3><p>Response time is another thing to test if your API is time critical. This time we don’t add this test on a request basis. We are programmers and we DRY. Checking for responses is going to be for each and every request, it’s better to add it at the collection level.</p><p>To add a test at the collection level, click on the collection name on the left panel. As already discussed, you’d see <strong>Authorization</strong>, <strong>Pre-request Script</strong>, <strong>Tests</strong> and <strong>Variables</strong>.</p><p>Navigate to <strong>Tests</strong>, and put this in the code area:</p><pre>pm.test(&quot;Response time is less than 500ms&quot;, function () {<br>    pm.expect(pm.response.responseTime).to.be.below(500);<br>});</pre><p>500ms is good enough for local testing. If your server is over the internet, you might need to modify it to suit your need.</p><p>This test will run for every request which is there in the collection and for each new request, you add to the collection.</p><h3>Run all tests from a collection</h3><p>When you click on a collection, you’ll see a Run button at the top right corner. When you click that, you’ll be asked which tests you want to run.</p><p>This is the Collection Runner UI. When you are done with all the config. Click on the <strong>Run Postman Premier</strong> to run all the tests and see the results.</p><h3>Conclusion</h3><p>We have learned enough Postman to get our wheels rolling. There’s much more to Postman than we have discussed in 2 articles on Fullstack with Santosh. Lots of features keep getting added in each release. You can keep yourself updated by following <a href="https://learning.postman.com/docs/getting-started/introduction/">Postman Docs</a>.</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2022/testing-http-requests-with-postman/"><em>https://santoshk.dev</em></a><em> on December 8, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209957d27849" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postman Premier — The Minimal Postman you need to Learn]]></title>
            <link>https://sntshk.medium.com/postman-premier-the-minimal-postman-you-need-to-learn-6814bcc7edb4?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6814bcc7edb4</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[postman]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Sun, 20 Nov 2022 18:24:07 GMT</pubDate>
            <atom:updated>2023-02-13T15:30:10.547Z</atom:updated>
            <content:encoded><![CDATA[<h3>Postman Premier — The Minimal Postman you need to Learn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*z6he1LUADWE3lTma.png" /></figure><h3>Introduction</h3><p>Welcome to my Fullstack with Santosh. Today we are going to learn about how to use Postman as a backend engineer to make our daily life easier. Postman is an API testing tool where you can test your REST APIs. It has now developed into handling many different kinds of interfaces, but today we are going to focus on the REST APIs.</p><p>Make sure you have Postman already installed. I work on Ubuntu and the way I install is sudo snap install postman. You can find instructions about your platform on the downloads page: <a href="https://www.postman.com/downloads/">https://www.postman.com/downloads/</a></p><p>When you open Postman for the first time, you might see a screen similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*No6_iBs4kJSJaWKM.png" /><figcaption>Postman home screen</figcaption></figure><p>Your home screen might appear a little different because 1. I have already signed in. 2. I have already created some workspaces. 3. I have changed the theme to dark.</p><h3>Create a collection</h3><p>Before you even start to test endpoints in your server, the first thing you’d do is create a collection. Press that little <strong>+</strong> button on the left column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*KproX1NBo1g0ZzE3.png" /><figcaption>Create new collection</figcaption></figure><p>Give it a name. I’m going to name it <strong>Postman Premier</strong>.</p><p>There are a lot more things that can be done with a Collection. But for now, let’s not get deep into it.</p><p>Note: If you don’t have an API to test, you can refer to my previous blog posts: <a href="https://santoshk.dev/posts/2022/building-a-bookstore-api-in-golang-with-gin/">Building a Book Store API in Golang With Gin</a> and <a href="https://santoshk.dev/posts/2022/how-to-integrate-swagger-ui-in-go-backend-gin-edition/">How to Integrate Swagger UI in Go Backend — Gin Edition</a> where I show how you can develop your simple CRUD server in Go. It’s worth a look.</p><h3>Working with Requests</h3><p>I am going to test my gingo server, which is a CRUD server I have developed before. I already have linked them above.</p><h3>Creating a GET Request to get introduced to UI</h3><p>I have already run my gingo server and I am going to make a GET request at <a href="http://localhost:8090/api/v1/books.">http://localhost:8090/api/v1/books.</a></p><p>Creating a request is straightforward in Postman. Let’s start with creating a GET request.</p><p>When you expand your created collection on the left column, you’ll see a link called <strong>Create a request</strong>. Click on that, and a tab will open in the main column.</p><p>In that window, a text will already be selected. This is the identifier of the request. I like to name my request the same as the path of the endpoint. In my case, I’m going to name it /books.</p><p>The next thing you do is select a <strong>verb</strong>. There is a dropdown just below the name of the request. This will by default be GET. For this particular request, we don&#39;t modify that.</p><p>Next, we’ll input the address of the endpoint we need to hit. I’ve input <a href="http://localhost:8090/api/v1/books.">http://localhost:8090/api/v1/books.</a></p><p>We don’t need any other setting for now. Don’t be intimidated by the UI if you don’t understand it yet.</p><p>I have recorded a gif for your reference. Here it goes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DxzRDSWpvIAe2RUO.gif" /><figcaption>Create a GET request</figcaption></figure><p>What we covered in this section: Creating a request, request name, request verb, and request path.</p><h3>Path Parameters</h3><p>We can get all books. Let us get a specific book; by ISBN.</p><p>The quickest way to create our next request is to duplicate the previous one and modify the duplicated one.</p><p>Let us name this new request /books/:isbn. For the path, we&#39;re going to use localhost:8090/api/v1/books/:isbn. As soon as you write :isbn in the path input, <strong>Params</strong> section will be highlighted.</p><p>When you navigate to that tab, you’d see isbn is already added as KEY in <strong>Path Variables</strong> section. You need to provide value. You can get ISBN from the response of the previous endpoint we tested. E.g. 9781612680194.</p><p>When you do this much, you should see a single book in the response, unlike the previous response, which had all the books.</p><p>Below is a gif for this section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*ktGVUQyqPHvS2Pxf.gif" /><figcaption>Working with path params</figcaption></figure><h3>Creating a POST Request and working with Body and Headers</h3><p>Duplicate the first endpoint we created again, but this time, change the verb to POST.</p><p>In the previous section <strong>Params</strong> section was highlighted. This time you need to highlight the <strong>Body</strong> section.</p><p>When you highlight <strong>Body</strong>, you’ll see a group of radio buttons. Click on the one labeled with <strong>raw</strong>. A dropdown will appear at the right with the text <strong>Text</strong>. Click on the dropdown and select <strong>JSON</strong>.</p><p>When you select JSON from the dropdown, a new header is added to the request. You can see the header when you highlight the <strong>Headers</strong> tab. In this tab, you can see many other headers already added by Postman.</p><p>When the header is set, use the following body to make a POST request:</p><pre>{<br>    &quot;isbn&quot;: &quot;9780137081073&quot;,<br>    &quot;title&quot;: &quot;The Clean Coder&quot;,<br>    &quot;author&quot;: &quot;Robert C. Martin&quot;<br>}</pre><p>Here is a gif of me doing the same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*0ps0UoWx1rE2-1PH.gif" /><figcaption>Working with body and header</figcaption></figure><p>For those who don’t know. Headers are not limited to POST requests. It might be required for a GET endpoint to have an auth token in its header.</p><p>Making requests for other verbs such as DELETE and PUT is no different. I left it over for you to try with those.</p><h3>Working with variables</h3><h3>Using Collection variables</h3><p>We have different variable scopes available when working with Postman:</p><p>Global &gt; Collection &gt; Environment &gt; Local</p><p>They all have their use case:</p><ul><li><strong>Global</strong> — Global variables are global to all the collections you have in Postman. This should be mostly avoided.</li><li><strong>Collection</strong> — This one is my favorite. You can have collection-level variables for say credentials, baseurl, etc.</li><li><strong>Environment</strong> — If you are testing a collection with multiple data sets or conditions. Environment variables come to use.</li><li><strong>Local</strong> — Local variables are local to request and will override all other scopes variables.</li></ul><p>I’ll demonstrate <strong>Collection</strong> variables, but all behave the same way and have similar UI.</p><p>Click on the Postman Premier collection and you’ll see 4 tabs. <em>Authorization</em>, <em>Pre-request Script</em>, <em>Tests</em> and <em>Variables</em>. Click on the variables.</p><p>Collection Variables use case: We are doing a lot of repetitions in each of the requests. We are inputting the base URL of the server each time. If we had to somehow modify the port address, we would have to modify it for all.</p><p>Let us change that to use a variable. If we ever need to change the value of the baseurl, we’ll only be changing that in a single place.</p><p>When you see the variables tab, you’ll see a table with 3 columns. Namely VARIABLE, INITIAL VALUE, and CURRENT VALUE. Set VARIABLE = baseUrl, INITIAL VALUE = http://localhost:8090/api/v1, CURRENT VALUE = http://localhost:8090/api/v1. INITIAL_VALUE and CURRENT_VALUE are the same here, but CURRENT_VALUE can be programmatically changed during request-response life cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*rBxVVnpgtGA0Kpyf.gif" /><figcaption>Working with collection variables</figcaption></figure><p>Now change all the occurrences of http://localhost:8090/api/v1 in the collection&#39;s URL section to {{baseUrl}}. This will be a manual process, but this is worth it.</p><h3>Saving response data in variables</h3><p>Why would you want to save response data in a variable?</p><p>That is a good question to ask. One such use case is user login. When you log in to a service, you’d get some kind of token with a certain validity time. That token is needed to make further requests. We can add a header using <strong>Pre-request script</strong> using the variable we save.</p><p>Our gingo server does not have a user authentication module right now. Let us try saving isbn from a GET request.</p><p>This may sound a little bit misleading, but anything you want to do after a request goes inside the <strong>Tests</strong> tab. This also includes setting a variable for a session.</p><p>Go to the <strong>Tests</strong> section of /books/:isbn and add this javascript code:</p><pre>const body = pm.response.json()<br>pm.collectionVariables.set(&quot;isbn&quot;, body.isbn);</pre><p>The code is straightforward. We are storing the JSON response in a const called body. Then we access the collection variable using pm.collectionVariables. We then set the variable name isbn with the value of body.isbn.</p><p>Here is me doing the same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*rXz4_ioBS4fBfxkT.gif" /><figcaption>Saving response data in variables</figcaption></figure><p>Similar to collection variables, we can set any scope of variable we discussed above.</p><h3>Conclusion</h3><p>In this post, we saw some basic use cases of Postman. In upcoming posts, we’ll see more advanced use cases. Until then, subscribe and stay updated.</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2022/postman-premier-the-minimal-postman-you-need-to-learn/"><em>https://santoshk.dev</em></a><em> on November 20, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6814bcc7edb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Logging Library for Golang]]></title>
            <link>https://sntshk.medium.com/best-logging-library-for-golang-44049868486d?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/44049868486d</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Sat, 22 Oct 2022 08:17:38 GMT</pubDate>
            <atom:updated>2023-02-12T11:21:26.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*H09lV1PZnPVNAFoS.png" /></figure><h3>Introduction</h3><p>I recently conducted a poll in the Go community regarding which logging library they use in their personal or professional project. The results were interesting. In this post I have jotted down the most favorite logging libraries and here is my opinion about them.</p><h3>Poll Results</h3><p>Here are the poll results that I conducted on <a href="https://www.reddit.com/r/golang/">r/golang</a>, <a href="https://twitter.com/i/communities/1493637136502960134">The Go Programming Language</a> community on Twitter, and <a href="https://www.linkedin.com/in/sntshk/">my LinkedIn following</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*8bculsKUkhEw9Qeg.png" /><figcaption>Poll results on r/golang</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*MSR9qne4Mf78ptRj.png" /><figcaption>Poll results on Twitter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*5nJa7NJ40YkWdU5_.png" /><figcaption>Poll results on LinkedIn</figcaption></figure><h3>Analysis of Results</h3><h4>Selection of the candidates</h4><p>For choosing the candidates for the poll, I didn’t do any thorough research. I was looking for a library to use in my <a href="https://gitlab.com/nunet/device-management-service">project at work</a>, and I ended up at <a href="https://github.com/sirupsen/logrus">sirupsen/logrus</a> which was already being used by one of the dependencies in that project.</p><p>After reading the README of the logrus, I noted it was in maintenance mode and no new feature was actively being developed. I still decided to use this library because logrus is a mature project and it has all the features which a logging library should have.</p><p>logrus README recommended using other libraries such as <a href="https://github.com/rs/zerolog">Zerolog</a>, <a href="https://github.com/uber-go/zap">Zap</a>, and <a href="https://github.com/apex/log">Apex</a>.</p><p>I started a poll on r/golang with these four candidates, but also came to know about <a href="https://github.com/golang/glog">glog</a> which was a go port of a C++ project by Google. I used that option in the poll conducted on LinkedIn.</p><p>I haven’t personally used any one of them yet.</p><h3>logrus</h3><p>Let’s talk about logrus first, it was the first library I landed upon when looking for one. The reason I looked at it first is that logrus was already one of the indirect dependencies of one of the dependencies in my project.</p><p>logrus stands 2nd in the place. zerolog is faster than logrus but there’s a reason it stands seconds among 4. It has been there for a while.</p><h3>zerolog</h3><p>The main reason you’d want to use zerolog if you are switching from logrus is the performance. <a href="https://santoshk.dev/tags/golang/">Go</a> is blazingly fast; but if your logger is making it slow, your application gets no benefit from being implemented in Go.</p><p>This is what zerolog’s README says:</p><blockquote><em>The zerolog package provides a fast and simple logger dedicated to JSON output.</em></blockquote><blockquote><em>Zerolog’s API is designed to provide both a great developer experience and stunning performance. Its unique chaining API allows zerolog to write JSON (or CBOR) log events by avoiding allocations and reflection.</em></blockquote><p><strong>zap</strong> is probably the most loved logging library for Go. Among <strong>817</strong> people who have voted on r/golang, <strong>315</strong> voted for zap.</p><p>According to the stats on their GitHub, zap is the fastest logger available there.</p><p>Also, zap only supports the two most recent minor versions of Go. So you might be locked with an older version of zap if your project for some reason is not able to update to the latest version of Go.</p><h3>Conclusion</h3><p>To have an opinion, I feel that I use them all before coming to a conclusion. But after this poll, I think I’m going to start using zap right away. What is your opinion? What factor was the responsible when you were choosing your logging library?</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2022/best-logging-library-for-golang/"><em>https://santoshk.dev</em></a><em> on October 22, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44049868486d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Release Dangling Elastic IPs Using the Lambda and Go SDKs]]></title>
            <link>https://medium.com/better-programming/release-dangling-elastic-ips-using-lambda-and-go-sdk-47a1b745150c?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a1b745150c</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Sat, 03 Sep 2022 02:04:35 GMT</pubDate>
            <atom:updated>2022-10-06T17:49:01.984Z</atom:updated>
            <content:encoded><![CDATA[<h4>An in-depth guide to save you money</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*WkEyLSnu70dGMaPf.png" /><figcaption>image by author</figcaption></figure><h3>Introduction</h3><p>Today, we are going to do a hands-on on how to kill a dangling EIP, or in other words, deallocate an unassigned Elastic IP. But before that, let’s talk about…</p><h3>What Is an Elastic IP, and Why Do We Need It?</h3><p>Elastic IPs are simply IP addresses provided by Amazon AWS. These are usually attached to internet gateways such as load balancers, or even EC2 instances. I have been using it with EC2 instances directly for my testing use case.</p><p>Normally, when you configure your EC2 instance to have a public IP but at the same time, you don’t use EIP. The problem is that when you stop and start your instance, your IP address is changed.</p><p>This is where Elastic IP shines. You attach an EIP to the EC2 instance and when you stop and start your instance, your IP won’t be changed.</p><p>This is extremely important if the EC2 you are running is hosting an internet-facing web server. Web servers shouldn’t generally frequently change their IPs.</p><h3>But Why Do We Need an EIP Killer?</h3><p>There is one good thing about EIP and one bad thing. The good thing is EIP is free to use. You don’t need to pay anything for the static IP you are using. How cool!</p><p>The bad thing is that when EIP is not attached to an instance, it costs you money. How warm!</p><p>It won’t cost you much if you leave it detached for a few hours. But as humans, we tend to forget if EIP is in use and only remember when we get our monthly bill.</p><p>In the Asia Pacific (Mumbai) region, if I forget to kill an EIP for a month, I get around a $4 bill. This was my main motivation to write this article.</p><p>With an EIP killer, I will be able to use Elastic IP with confidence by releasing it when not in use.</p><h3>Get Started</h3><p>What we’ll work with:</p><ul><li>AWS Lambda</li><li>Go</li><li>AWS Go SDK</li><li>AWS CLI</li></ul><p>What we’re going to do:</p><ul><li>Run a Lambda on a predefined interval</li><li>Use this Lambda with the AWS SDK to check if any dangling EIP is lying around</li><li>If dangling EIP is found, deallocate, that is, kill it</li></ul><p>Initially, I was going to use Python for the Lambda runtime, but Go is faster than Python. We are going to benefit from this decision as we can run our function for a smaller time span. This is important because we plan to run our Lambda at frequent intervals.</p><p>With this post, I mostly plan to expand my knowledge in the field of serverless computing. I intend to touch Lambda, EventBridge, and related constructs.</p><h3>Phase 1: Provision a Lambda function</h3><p>The main task in this phase is to manually create a function. In the second phase, we’ll see what is the logic for killing the EIPs. Let’s get started.</p><ol><li>Go through the web UI and choose to create a function.</li><li>Keep “Author from scratch” selected.</li><li>Fill in the name. I like to call it the “eip-killer.”</li><li>Select the runtime to be Go 1.x.</li><li>Keep everything else on default. Hit Create function.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*VCdYIs2xdor1gsclRPsn7Q.png" /><figcaption>Create Lambda func from Web UI</figcaption></figure><p><strong>Note</strong>: Creating Lambda with default settings also creates an IAM role. This IAM role dictates how this Lambda interacts with other AWS services. By default, this role allows Lambda to talk with CloudWatch to put logs. You can add more policies to this role when working with other AWS services.</p><p>Let’s go ahead and do a quick invoke to test if the function is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3b-ks1mmBrsi91Hpl0tDg.png" /><figcaption>Invoke result of Lambda</figcaption></figure><p>Our EIP-killer is alive. But doesn’t know how to kill. Let’s teach it in the next phase.</p><h3>Phase 2: Write the EIP-Killing Logic</h3><p>While testing, you might have got a view of the Code tab of the function which says, “The code editor does not support the Go 1.x runtime.” What this means for us developers is that we have to use our text editor to write the logic and upload the prebuilt binary to Lambda.</p><p>The prime documentation for Go AWS SDK is <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-golang.html">https://docs.aws.amazon.com/lambda/latest/dg/lambda-golang.html</a>, but don’t worry. I’ll filter out the required material required for this post.</p><h3>Phase 2.1: The Initial Deployment Process</h3><p>Before we write the actual logic, let’s write a simple “Hello EIP Killer” code to get the awareness of the process required for uploading the code.</p><ol><li>Create a workspace for our Lambda code.</li></ol><pre>mkdir eip-killer<br>cd eip-killer</pre><p>2. Initialize a go module in the folder.</p><pre>go mod init EIP-killer</pre><p>You could also put the GitHub/GitLab URL of the repo where you intend to put your Lambda code.</p><p>3. Create a main.go and put this code into it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f4517b6ff0aaaaaba67c97fd14552ac/href">https://medium.com/media/7f4517b6ff0aaaaaba67c97fd14552ac/href</a></iframe><p>As we are using external dependency, get it with this command:</p><pre>go get github.com/aws/aws-lambda-go/lambda</pre><p>4. Build a binary out of main.go:</p><pre>GOOS=linux GOARCH=amd64 go build -o main main.go</pre><p>Remember while creating the function we had selected the architecture to be x86_64. So, we need to reflect that with GOARCH=amd64.</p><p>5. Zip the binary. Upload the zip to function.</p><pre>zip main.zip main</pre><p>Upload using this command:</p><pre>aws lambda update-function-code --function-name eip-killer --zip-file fileb://main.zip</pre><p>While this could have been enough, the default handler (where lambda begins executing) in function with factory settings is hello. But our code uses main. So we need to update the handler config to match that.</p><p>We need this update only once.</p><pre>aws lambda update-function-configuration --function-name eip-killer --handler main</pre><p>After this, when you run the func:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*Rf6odBBD_mTR9FqhaXPYzg.png" /><figcaption>Updated function</figcaption></figure><p>You can roam around this path: <a href="https://github.com/aws/aws-lambda-go">https://github.com/aws/aws-lambda-go</a> if you want to dig deeper into Go+Lambda. But for now, I’m going to use AWS SDK to do our magic.</p><h3>Phase 2.2: Logic to Deallocate Unused EIPs</h3><p>Open up the main.go again and write the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e71bd84418c10012fa0ad4fd04925cc/href">https://medium.com/media/9e71bd84418c10012fa0ad4fd04925cc/href</a></iframe><p>Quite a large source code. Let us understand it line by line.</p><p>Line 14–16 declares an event struct. This struct is going to be a parameter to the Handler function.</p><p>On line 18, we see a function with the signature Handler(ctx context.Context, name MyEvent) (string, error). Handler here is the name of the function.</p><p>The first parameter to the handler is the context object. If you are working with web services in golang, you must be aware of that.</p><p>Next is our MyEvent which is defined above. This is as per Lambda&#39;s spec.</p><p>Our handler function also returns a string and an error, which is then bubbled to Lambda logs.</p><p>Line 20 deals with configuration. Please note that we are using AWS SDK. And the SDK can run on platforms other than Lambda. On the local system, the default config is located at ~/.aws/config. But on Lambda, it automatically loads the region it’s running in.</p><p>On line 26, we create a new EC2 client to interact with our AWS account. We initialize this client with the config instance we created on line 15.</p><p>On line 29, we have initialized a filter for IPs. This seems to be an added step. But this variable is going to be a mandatory parameter for our next command.</p><p>On line 32, we get a list of all Elastic IPs associated with our account. There are no filters to the result as we have not specified any filter on line 29.</p><p>It’s time to look at the isThisEIPKillable function which is from 69 to 76. This is an extra feature for flexibility. This will forgive any EIP which has the tag KILLERHOLD set to true. So, when you have an EIP you don&#39;t want to kill, you set this tag to it. This is good for the experiment as our Lambda will be running on a one-hour (configurable by user) interval, and it might not be desired outcome to delete them every hour.</p><p>Let’s get back to our main flow. We have a result variable with all the addresses in it. On line 40, we check if the IP is associated with any EC2 or not. Then we run the helper function we just discussed. If all is okay, meaning that KIP can be released, we go ahead and release the address back to the AWS pool.</p><p>On lines 57–59, if EIP is associated with any EC2, we print some metadata about the EIP association.</p><p>That’s it. It was not that hard to understand, isn’t it? Before we deploy it, let’s create some EIP and not allocate it to any EC2. We’ll also have some EIP having KILLERHOLD set to true.</p><h3>Phase 2.3: Give Lambda Permission To Release and Read EIPs</h3><p>I hope you have updated your lambda function and pushed the zip file to the function. Review Phase 2.1 if you have not. Continue reading if you did.</p><p>Before I test it with actual EIPs, I wanted to show something else. Right now if you try to test the function, you’d see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ-sRJs1aPI6Q1Rfv4HWAw.png" /><figcaption>Lambda is not able to access EIPs</figcaption></figure><p>If you clearly read the error message, it says that the API call returned 403. Meaning that Lambda was not authorized to make the call to EIP APIs.</p><p>To overcome this problem, we need to give access to Lambda to read some metadata from EC2.</p><p>When no Lambda Web UI for the function. If you go to Configuration &gt; Permission &gt; Execution role as described in the image below. You’ll see a role was created while we created the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*lUu3il4HfGDoaVLmvsQzSA.png" /><figcaption>Permission configuration for Lambda</figcaption></figure><p>Click on that and you’ll be taken to the IAM page for that role.</p><p>When on that page, look for a dropdown named Add permissions and click on Create inline policy.</p><p>Switch from Visual editor to JSON, and paste this policy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7a902b32bd92d839c7976166a73a6c5/href">https://medium.com/media/e7a902b32bd92d839c7976166a73a6c5/href</a></iframe><p>As you can see, in the Action section, we have added permission for ec2:ReleaseAddress, and ec2:DescribeAddresses.</p><p>Review policy and give it a name, and then Create policy.</p><p>When done, you’d see this policy in the list of policies attached to the role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*xHjw0REcjAPek9s1IzO9wA.png" /><figcaption>Inline policy attached to role</figcaption></figure><h3>Phase 2.3: Test our EIP killer</h3><p>We are not set for the actual testing.</p><p>We are going to allocate three Elastic IPs for our testing purpose:</p><ul><li>We’ll attach one to the EC2 instance</li><li>The second will be dangling</li><li>And the third one will be also dangling but will have our KILLERHOLD set to true.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*y-GjMUGeITz0HKIBC1MI7A.png" /><figcaption>EIP set for testing</figcaption></figure><p>To actually invoke the function (apart from testing it), one way is to create a public URL. We can also invoke through the AWS CLI, but I’m not choosing that for now. You can do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*QFTv-SQxXyzcBENrbuwHNQ.gif" /><figcaption>Create a public URL for lambda</figcaption></figure><p>Then I went ahead and opened that URL to execute the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/0*FRP-akY_k4KaCd2s.png" /><figcaption>Lambda invoked by visiting public URL</figcaption></figure><p>You can configure AWS API Gateway in front of the function. But that’s out of the scope of this post.</p><p>Next, we see the result of the invocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*FFzS78mypSc28wLY.png" /><figcaption>The result after EIP Killer execution</figcaption></figure><p>That’s the end of Phase 2. We can kill EIPs now. How wonderful.</p><h3>Phase 3: Trigger Lambda at a One-Hour Interval</h3><p>The main part of the EIP killer is already developed. Let’s now execute it at a one-hour interval as planned before.</p><h3>Phase 3.1: Configure EventBridge aka CloudWatch Events</h3><p>We are going to emit an event at our one-hour interval and we are going to use EventBridge for this.</p><p>I have recorded a screencast gif to preserve space in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k0B-SbTJ_bARsExc.gif" /><figcaption>Configure EventBridge to emit event in 1 hour</figcaption></figure><p>Once done, this event should appear in the Trigger section of the Lambda function, as seen in the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*jGclaR8pkoyPrQDw.png" /><figcaption>Trigger config showing EventBridge rule</figcaption></figure><h3>Phase 3.2: Create an EIP and Go To Sleep</h3><p>As I’m writing this article at 4 a.m., I’m going to create an EIP and go to sleep. Will check in the morning if our setup is working.</p><p><em>A few hours later…</em></p><p>I woke up this morning with only one EIP.</p><p>And this is how we gonna achieve this killing in one hour. You can configure the interval, but I think this is optimal. You also don’t need to have a public IP for this. So if you have, you can delete it from the web interface now.</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2022/release-dangling-elastic-ips-using-lambda-and-go-sdk/"><em>https://santoshk.dev</em></a><em> on September 3, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a1b745150c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/release-dangling-elastic-ips-using-lambda-and-go-sdk-47a1b745150c">Release Dangling Elastic IPs Using the Lambda and Go SDKs</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</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 Integrate Swagger UI in Go Backend — Gin Edition]]></title>
            <link>https://sntshk.medium.com/how-to-integrate-swagger-ui-in-go-backend-gin-edition-b69546cd1149?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b69546cd1149</guid>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Thu, 26 May 2022 13:40:52 GMT</pubDate>
            <atom:updated>2022-05-29T17:37:47.823Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Integrate Swagger UI in Go Backend — Gin Edition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*AYHGHrBdGnLMe52m.png" /></figure><h3>Introduction</h3><p>Unlike FastAPI, Gin does not have OpenAPI integration built in. With FastAPI when you add a route, documentation is already generated. With Gin, this is not the case. But recently I integrated Swagger UI in one of my Go backends and I wanted to document that process.</p><h3>Prerequisites</h3><ul><li>An already running Gin server</li></ul><p>You might consider <a href="https://santoshk.dev/posts/2022/building-a-bookstore-api-in-golang-with-gin/">Building a Book Store API in Golang With Gin</a> if you are starting from scratch. I’ll be using the same book store and extending over it to integrate Swagger UI.</p><h3>How Swagger works with Gin</h3><p>The way Swagger works with other Go backend is not different they all have the same mechanism. But how does it really work and what do we have to really do?</p><p>Swagger uses the Go comment system which is very well integrated with documentation already as we know. We write comments in a pre-defined way, details of which we will see further ahead in the post. But mostly it is divided into 2 parts. The server itself and the routes.</p><p>Swagger has a CLI binary which when runs converts these comment documents into OpenAPI compliant documentation. The resultant file also includes OpenAPI server specs in JSON and YAML format.</p><p>Lastly, we route the generated content via a handler in our backend.</p><p>How do we do that? Let’s see.</p><h3>Setup Swagger CLI</h3><p>The prime repository you should keep under your pillow is <a href="https://github.com/swaggo/swag">https://github.com/swaggo/swag</a>. Both in terms of CLI and documentation.</p><p>We’ll install a CLI application called swag. Here&#39;s how:</p><pre>go get -u github.com/swaggo/swag/cmd/swag</pre><pre># 1.16 or newer<br>go install github.com/swaggo/swag/cmd/swag@latest</pre><p>The first command will download the dependencies to integrate in the server application.</p><p>The second one is where we install the CLI.</p><p>Now you should be able to run the swag command:</p><pre>$ swag -h<br>NAME:<br>   swag - Automatically generate RESTful API documentation with Swagger 2.0 for Go.</pre><pre>USAGE:<br>   swag [global options] command [command options] [arguments...]</pre><pre>VERSION:<br>   v1.8.1</pre><pre>COMMANDS:<br>   init, i  Create docs.go<br>   fmt, f   format swag comments<br>   help, h  Shows a list of commands or help for one command</pre><pre>GLOBAL OPTIONS:<br>   --help, -h     show help (default: false)<br>   --version, -v  print the version (default: false)</pre><h3>Documenting the Gin Server</h3><p>When you look at Swagger UI documentation for any OpenAPI enabled website, you’d see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvBe0lNRLF_4fzI2H5O5GQ.png" /><figcaption>Petstore Swagger UI Docs</figcaption></figure><p>You might be familiar with the low half part of the UI. This is what Swagger docs are for i.e. to document the routes.</p><p>But before we deal with the lower 50% part I want you to notice in the above picture is the top 50% part. Right from the <strong>Swagger Petstore</strong> header to <strong>Find out more about the Swagger</strong> anchor link.</p><p>This part shows the metadata about the API server itself. In this section, we are going to build that part. You can find the <a href="https://github.com/santosh/gingo/tree/91cafb5e19f3bbc3be9135ba74f8883d74941651">code to start with here</a>. We’ll be continuing on that code.</p><p>First of all, we need to go get the packages we need to work with:</p><pre>go get -u github.com/swaggo/files<br>go get -u github.com/swaggo/gin-swagger</pre><p>Now after we have done that, let&#39;s look at our main.go file. This is the main.go at the moment:</p><pre>package main</pre><pre>import &quot;github.com/santosh/gingo/routes&quot;</pre><pre>func main() {<br> router := routes.SetupRouter()</pre><pre>router.Run(&quot;:8080&quot;)<br>}</pre><h3>Add a route for Swagger Docs</h3><p>We add a new router in the main function:</p><pre>router.GET(&quot;/docs/*any&quot;, ginSwagger.WrapHandler(swaggerFiles.Handler))</pre><p>The modified file would look like this:</p><pre>-import &quot;github.com/santosh/gingo/routes&quot;<br>+import (<br>+       &quot;github.com/santosh/gingo/routes&quot;<br>+       swaggerFiles &quot;github.com/swaggo/files&quot;<br>+       ginSwagger &quot;github.com/swaggo/gin-swagger&quot;<br>+)<br> <br> func main() {<br>        router := routes.SetupRouter()<br> <br>+       router.GET(&quot;/docs/*any&quot;, ginSwagger.WrapHandler(swaggerFiles.Handler))<br>+<br>        router.Run(&quot;:8080&quot;)<br> }</pre><p>swaggerFiles.Handler here is the handler which has all the assets embedded in it. Assets like the HTML, CSS, and javascript files are shown on the documentation end.</p><p>ginSwagger.WrapHandler is a wrapper around http.Handler, but for Gin.</p><p>This should be enough for testing. Let’s see how the docs render at &lt;server address&gt;/docs/index.html.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*es4GlQbQUGz1eFfzqaxC4g.png" /><figcaption>Docs loaded, but API definition didn’t load</figcaption></figure><p>The good news is API documentation site is up. The bad news is it does not look like a normal API documentation site. What did we miss?</p><h3>Generate swagger docs every time you modify doc string</h3><p>Swagger documentation is stored in Go’s own docstring. We have a special syntax that we follow. More on that later. But first, let us learn how to generate docs.</p><pre>swag init<br>2022/05/25 23:59:16 Generate swagger docs....<br>2022/05/25 23:59:16 Generate general API Info, search dir:./<br>2022/05/25 23:59:16 create docs.go at  docs/docs.go<br>2022/05/25 23:59:16 create swagger.json at  docs/swagger.json<br>2022/05/25 23:59:16 create swagger.yaml at  docs/swagger.yaml</pre><p>We run swag init every time we update docs for our API. This generates 3 files inside a sub directory called docs/.</p><pre>$ tree docs<br>docs<br>├── docs.go<br>├── swagger.json<br>└── swagger.yaml</pre><pre>0 directories, 3 files</pre><p>swagger.json and swagger.yaml are the actual specification which you can upload to services like AWS API Gateway and similar services. docs.go is a glue code that we need to import into our server.</p><p>Let us now import the documentation to our main.go.</p><pre>package main<br> <br> import (<br>+       _ &quot;github.com/santosh/gingo/docs&quot;<br>        &quot;github.com/santosh/gingo/routes&quot;<br>        swaggerFiles &quot;github.com/swaggo/files&quot;<br>        ginSwagger &quot;github.com/swaggo/gin-swagger&quot;<br> )<br> <br>+// <a href="http://twitter.com/title">@title</a>     Gingo Bookstore API<br> func main() {<br>        router := routes.SetupRouter()</pre><p>As you can see we have imported docs the module by giving the full path of the module. We also have to prepend this import using _ because it is not explicitly used in main.go file.</p><p>You might also have noticed // @title Gingo Bookstore API line. Please note its position as this is important. It is just above the main() func. Also @title is not random here. It is one of the keywords which is documented under <a href="https://github.com/swaggo/swag#general-api-info">General API Info</a>. We&#39;ll see more of these as we go, but for now, let&#39;s regenerate our docs and review the API docs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*rkb5_6FZpsyXjwudS-MR8A.png" /><figcaption>Working API Docs</figcaption></figure><p>Looks like we are getting somewhere. :D</p><h3>Add General API Info to Gin API Server</h3><p>We saw @title annotation in the last section. It is used to set the title for the API server. But it is not the only annotation available. There is <a href="https://github.com/swaggo/swag#general-api-info">a wide array of annotation in Swagger</a>. You can find them in use <a href="https://github.com/swaggo/swag/blob/master/example/celler/main.go#L16-L57">in real life here</a>.</p><p>I’m going to use some of them to construct metadata on my doc site.</p><pre>// @title           Gin Book Service<br>// @version         1.0<br>// @description     A book management service API in Go using Gin framework.<br>// @termsOfService  https://tos.santoshk.dev</pre><pre>// @contact.name   Santosh Kumar<br>// @contact.url    https://twitter.com/sntshk<br>// @contact.email  sntshkmr60@gmail.com</pre><pre>// @license.name  Apache 2.0<br>// @license.url   http://www.apache.org/licenses/LICENSE-2.0.html</pre><pre>// @host      localhost:8080<br>// @BasePath  /api/v1</pre><ol><li>Run swag init .</li><li>Re-run the server.</li><li>Check for update:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*bRVG53-i6xpOATtCLGW-Bw.png" /><figcaption>Swagger API Server with Metadata</figcaption></figure><p>That’s some metadata in there.</p><p>You might also have noticed that the API spec inside docs/ directory has changed. For example, here is the swagger.yaml file from the docs/ dir.</p><pre>{<br>     &quot;swagger&quot;: &quot;2.0&quot;,<br>     &quot;info&quot;: {<br>-        &quot;title&quot;: &quot;Gingo Bookstore API&quot;,<br>-        &quot;contact&quot;: {}<br>+        &quot;description&quot;: &quot;A book management service API in Go using Gin framework.&quot;,<br>+        &quot;title&quot;: &quot;Gin Book Service&quot;,<br>+        &quot;termsOfService&quot;: &quot;<a href="https://tos.santoshk.dev/">https://tos.santoshk.dev</a>&quot;,<br>+        &quot;contact&quot;: {<br>+            &quot;name&quot;: &quot;Santosh Kumar&quot;,<br>+            &quot;url&quot;: &quot;<a href="https://twitter.com/sntshk">https://twitter.com/sntshk</a>&quot;,<br>+            &quot;email&quot;: &quot;<a href="/service/mailto:sntshkmr60@gmail.com">sntshkmr60@gmail.com</a>&quot;<br>+        },<br>+        &quot;license&quot;: {<br>+            &quot;name&quot;: &quot;Apache 2.0&quot;,<br>+            &quot;url&quot;: &quot;<a href="http://www.apache.org/licenses/LICENSE-2.0.html">http://www.apache.org/licenses/LICENSE-2.0.html</a>&quot;<br>+        },<br>+        &quot;version&quot;: &quot;1.0&quot;<br>     },<br>+    &quot;host&quot;: &quot;localhost:8080&quot;,<br>+    &quot;basePath&quot;: &quot;/api/v1&quot;,<br>     &quot;paths&quot;: {}<br> }</pre><p>Now it’s time to add docs for API endpoints.</p><h3>Add API Operation Info to API Endpoints</h3><p>Just like General API Info for the main server, there also is <a href="https://github.com/swaggo/swag#api-operation">API Operation</a> for individual routes/endpoints handlers.</p><p>They are more diverse than what I’m going to use here. The ones I’m going to use are just a subset of them. If you want to check out some real examples, you can <a href="https://github.com/swaggo/swag/tree/master/example/celler/controller">find them here</a> on each of the route handlers.</p><p>Here is modified handlers/books.go:</p><pre>&quot;github.com/santosh/gingo/models&quot;<br> )<br> <br>-// GetBooks responds with the list of all books as JSON.<br>+// GetBooks             godoc<br>+// @Summary      Get books array<br>+// @Description  Responds with the list of all books as JSON.<br>+// @Tags         books<br>+// @Produce      json<br>+// @Success      200  {array}  models.Book<br>+// @Router       /books [get]<br> func GetBooks(c *gin.Context) {<br>        c.JSON(http.StatusOK, db.Books)<br> }<br> <br>-// PostBook takes a book JSON and store in DB.<br>+// PostBook             godoc<br>+// @Summary      Store a new book<br>+// @Description  Takes a book JSON and store in DB. Return saved JSON.<br>+// @Tags         books<br>+// @Produce      json<br>+// @Param        book  body      models.Book  true  &quot;Book JSON&quot;<br>+// @Success      200   {object}  models.Book<br>+// @Router       /books [post]<br> func PostBook(c *gin.Context) {<br>        var newBook models.Book<br> <br>@@ -28,7 +41,14 @@ func PostBook(c *gin.Context) {<br>        c.JSON(http.StatusCreated, newBook)<br> }<br> <br>-// GetBookByISBN locates the book whose ISBN value matches the isbn<br>+// GetBookByISBN                godoc<br>+// @Summary      Get single book by isbn<br>+// @Description  Returns the book whose ISBN value matches the isbn.<br>+// @Tags         books<br>+// @Produce      json<br>+// @Param        isbn  path      string  true  &quot;search book by isbn&quot;<br>+// @Success      200  {object}  models.Book<br>+// @Router       /books/{isbn} [get]<br> func GetBookByISBN(c *gin.Context) {<br>        isbn := c.Param(&quot;isbn&quot;)</pre><ol><li>Run swag init .</li><li>Re-run the server.</li><li>Check for updates:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*pb9tLfYuctb-EKjYABcRfg.png" /><figcaption>Swagger UI; with documented routes</figcaption></figure><p>And here is the updated swagger.yaml:</p><pre>basePath: /api/v1<br>+definitions:<br>+  models.Book:<br>+    properties:<br>+      author:<br>+        type: string<br>+      isbn:<br>+        type: string<br>+      title:<br>+        type: string<br>+    type: object<br> host: localhost:8080<br> info:<br>   contact:<br>@@ -12,5 +22,58 @@ info:<br>   termsOfService: <a href="https://tos.santoshk.dev/">https://tos.santoshk.dev</a><br>   title: Gin Book Service<br>   version: &quot;1.0&quot;<br>-paths: {}<br>+paths:<br>+  /books:<br>+    get:<br>+      description: Responds with the list of all books as JSON.<br>+      produces:<br>+      - application/json<br>+      responses:<br>+        &quot;200&quot;:<br>+          description: OK<br>+          schema:<br>+            items:<br>+              $ref: &#39;#/definitions/models.Book&#39;<br>+            type: array<br>+      summary: Get books array<br>+      tags:<br>+      - books<br>+    post:<br>+      description: Takes a book JSON and store in DB. Return saved JSON.<br>+      parameters:<br>+      - description: Book JSON<br>+        in: body<br>+        name: book<br>+        required: true<br>+        schema:<br>+          $ref: &#39;#/definitions/models.Book&#39;<br>+      produces:<br>+      - application/json<br>+      responses:<br>+        &quot;200&quot;:<br>+          description: OK<br>+          schema:<br>+            $ref: &#39;#/definitions/models.Book&#39;<br>+      summary: Store a new book<br>+      tags:<br>+      - books<br>+  /books/{isbn}:<br>+    get:<br>+      description: Returns the book whose ISBN value matches the isbn.<br>+      parameters:<br>+      - description: search book by isbn<br>+        in: path<br>+        name: isbn<br>+        required: true<br>+        type: string<br>+      produces:<br>+      - application/json<br>+      responses:<br>+        &quot;200&quot;:<br>+          description: OK<br>+          schema:<br>+            $ref: &#39;#/definitions/models.Book&#39;<br>+      summary: Get single book by isbn<br>+      tags:<br>+      - books<br> swagger: &quot;2.0&quot;</pre><p>Notice the new definitions and paths section added. It is for models and the endpoints respectively.</p><h3>Bonus: Router Group for /api/v1</h3><p>It is always a good idea to prepend your routes with api/v1. v1 bit has a logic behind it. It is for the time when you have to introduce a breaking change which is not backward compatible. Maybe the input or the output has changes that might break millions of dependent client.</p><p>In these situations, you increment the version to something like api/v2 and let the older API server serve old from the old handler.</p><p>Right now all of the routes in gingo server start with /book. We are going to change that.</p><p>Here is the modified routes/routes.go.</p><pre>func SetupRouter() *gin.Engine {<br>        router := gin.Default()<br>-       router.GET(&quot;/books&quot;, handlers.GetBooks)<br>-       router.GET(&quot;/books/:isbn&quot;, handlers.GetBookByISBN)<br>-       // router.DELETE(&quot;/books/:isbn&quot;, handlers.DeleteBookByISBN)<br>-       // router.PUT(&quot;/books/:isbn&quot;, handlers.UpdateBookByISBN)<br>-       router.POST(&quot;/books&quot;, handlers.PostBook)<br>+<br>+       v1 := router.Group(&quot;/api/v1&quot;)<br>+       {<br>+               v1.GET(&quot;/books&quot;, handlers.GetBooks)<br>+               v1.GET(&quot;/books/:isbn&quot;, handlers.GetBookByISBN)<br>+               // router.DELETE(&quot;/books/:isbn&quot;, handlers.DeleteBookByISBN)<br>+               // router.PUT(&quot;/books/:isbn&quot;, handlers.UpdateBookByISBN)<br>+               v1.POST(&quot;/books&quot;, handlers.PostBook)<br>+       }<br> <br>        return router<br> }</pre><p>Here we use router.Group to create a group with a path of /api/v1. We then move all the route definitions into the group and surround it with braces. That is how we create a path route in Gin.</p><h3>Conclusion</h3><p>API documentation is an essential part of API documentation. Instead of documenting the endpoints anywhere else, we can document the routes right in the code. That way we only have 1 single source of truth. No need to maintain code and documentation separately. In turn, we get always up-to-date documentation.</p><p>Every backend server has some sort of support for Swagger UI. I have covered the basics for Gin, but if you use any other framework, I encourage you to look for your own framework.</p><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2022/how-to-integrate-swagger-ui-in-go-backend-gin-edition/"><em>https://santoshk.dev</em></a><em> on May 26, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b69546cd1149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC for Absolute Beginners, in Go]]></title>
            <link>https://sntshk.medium.com/grpc-for-absolute-beginners-in-go-43b39a49596b?source=rss-cf8f28329b2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/43b39a49596b</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[protobuf]]></category>
            <dc:creator><![CDATA[Santosh Kumar]]></dc:creator>
            <pubDate>Mon, 16 May 2022 16:25:04 GMT</pubDate>
            <atom:updated>2022-05-22T13:55:05.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uBHAPbl43CUdh9tx.jpg" /></figure><h3>Introduction</h3><p>The Internet has evolved in the last 2 decades a lot. HTTP/1.1 was not enough so we have HTTP2 now. The specification we used to transfer data between the client and the server has also evolved. From XML to JSON, now we have Protocol Buffer, which is a binary spec. Let’s dive deeper.</p><p>The picture below from Wikipedia shows how exponential data is growing.</p><figure><img alt="Rapid growth of data" src="https://cdn-images-1.medium.com/max/960/1*GUV9-peQPQOYL84_bVBysQ.png" /><figcaption>Rapid growth of data</figcaption></figure><h3>Prerequisites</h3><ul><li>Go</li><li>HTTP2</li></ul><h3>Enough HTTP2 to know gRPC</h3><p>During the early days of the web, we only had static content, hardly text files, and HTML files. After then, the web grew a bit and the web server and clients started to deal with rich media like rich texts, images, and videos. Servers also started to serve dynamic content based on what clients request.</p><p>This was the start of the RPC era. A client would hit a certain endpoint with certain data, and the server’s work was to respond to that request. In the early time of RPC, XML was extensively used. We still use XML in some systems. But most of the world has moved to JSON as a communication format between the server and the client.</p><p>Now, over time, everything has evolved. One of the things which evolved is HTTP spec. Now we have HTTP2. HTTP2 is the base of gRPC. Certain properties make HTTP2 a nurturing ground for gRPC.</p><h4>HTTP/1.1</h4><ul><li>The header is plaintext and not compressed</li><li>Spawns a new TCP connection on each request</li><li>TLS is not required</li></ul><h4>HTTP/2</h4><ul><li>The header is compressed and binary</li><li>uses already existing TCP connection</li><li>Requires TLS by default, enhanced security</li></ul><h3>Let’s learn about Protocol Buffer first</h3><p>We have seen how HTTP2 is essential for gRPC, now let’s see where Protocol Buffer stands.</p><p>Although you can use gRPC with JSON, Protocol Buffer brings new things to the table. We saw that for a long time, JSON was used to send data back and forth between servers and clients. Now, what has happened is that we have taken yet another step to move from JSON to its successor.</p><p>Protocol buffers are building block of gRPC and is a replacement for JSON. Protocol Buffer inherits a lot from HTTP/2.</p><h4>JSON</h4><ul><li>Plaintext</li><li>Larger payload over wire</li><li>Write your server</li></ul><h4>Protocol Buffer</h4><ul><li>Binary</li><li>Smaller payload over wire</li><li>.proto files can create server stub</li><li>As we already know, HTTP/2 is binary. So are protocol buffers. Now you don’t need to pass a date as a string in JSON. You can pass BSON over the wire.</li><li>It is easy on a network as we only use the space we need to use. Say int32 only uses 4 bytes of data. The same data in JSON (string) could have used multiple bytes for a longer integer value.</li><li>We write .proto files. the proto compiler generates stub files which can be used to write the server as well as the client. The key takeaway here is we can use the same proto files to generate clients and servers in many different languages.</li><li>Protocol Buffers are agnostic to the language you are working with to develop your server or the client. .proto files have their syntax and data types which convert to specific data types in a destination programming language. This is my favorite reason to use gRPC in my projects.</li></ul><p>I recommend you to read through the proto syntax, keywords, and data types here: <a href="https://developers.google.com/protocol-buffers/docs/proto3">https://developers.google.com/protocol-buffers/docs/proto3</a></p><h3>What is gRPC?</h3><p>Ever heard of RPC? It stands for Remote Procedure Call. It’s an old way of running a remote procedure on a remote machine. Let me make it a little familiar for you. When you hit an endpoint from a frontend to a backend, you make a remote call or a remote procedure call.</p><p>SOAP and REST both are an example of RPC. You can send data in the body and hit an API on the other end. That’s how it has been happening since the start.</p><p>gRPC is a continuation of that SOAP and REST. gRPC brings all the advancements that their ancestors can’t. With gRPC, a client application can directly call a method on a server application on a different machine as if it were a local object.</p><h3>Types of Service Methods in gRPC</h3><p>We’ll practically see what service methods are when we do hands-on with code. But right now I want to specify that in gRPC we have 4 kinds of method definitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wxwbyrl8YOTSUSkrW3XyHg.jpeg" /><figcaption>Types of Service Methods</figcaption></figure><ol><li><strong>Unary</strong> — Unary is similar to a normal REST call. A client initiates a TCP connection, sends a message, waits for the server to respond, and finally, the server responds.</li><li><strong>Server Streaming</strong> — Server streaming RPCs where the client sends a request to the server and gets a stream to read a sequence of messages back. For example, you searched for a keyword. Instead of returning a static page, Twitter returns a stream of tweets, including whatever is being tweeted in real time.</li><li><strong>Client Streaming</strong> — Client streaming RPCs where the client writes a sequence of messages and sends them to the server. Once the client has finished writing the messages, it waits for the server to read them and return its response. Again gRPC guarantees message ordering within an individual RPC call. An example of it would be an IoT device (e.g. a car) streaming its device location to the central server (e.g. Uber).</li><li><strong>Bidirectional Streaming</strong> — Bidirectional streaming RPCs where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like. An example of this would be a chat application. But I know there are more complex use cases available in the wild. Please let me know in the comments if you do so.</li></ol><p>For a detailed explanation of what happens when a gRPC client calls a gRPC server method, please consider reading <a href="https://grpc.io/docs/what-is-grpc/core-concepts/#rpc-life-cycle"><strong>RPC life cycle</strong></a>.</p><h3>Developing with gRPC</h3><p>We have had enough of theories. Let’s develop some code to see this thing in action.</p><p>We are going to have an example in Go. Although as we already know, the proto files have a language of their own which is used to generate code in multiple languages.</p><p>We are going to write a simple calculator app.</p><h3>Write the proto file</h3><p>.proto files are contracts between the server and the client. This is similar to the REST API you have already experienced with.</p><p>Before I proceed further, I’d like to inform you that having the whole code into a module will make your life easy. That’s the reason, I’ve created a go module at the root of the directory named github.com/santosh/example.</p><h4>calculator/calculator.proto</h4><pre>syntax = &quot;proto3&quot;;<br><br>option go_package = &quot;github.com/santosh/example/calculator&quot;;<br><br>package calculator;<br><br>// The calculator service definition.<br>service Calculator {<br>    // Adds two number<br>    rpc Add(Input) returns (Output);<br>}<br><br>// Input message containing two operands<br>message Input {<br>    int32 Operand1 = 1;<br>    int32 Operand2 = 2;<br>}<br><br>// Output message containing result of operation<br>message Output {<br>    int32 Result = 1;<br>}</pre><h3>Explanation</h3><p>Protocol buffer data is structured as messages, where each message is a small logical record of information containing a series of name-value pairs called fields. Line 7–10 is an example of a message. So is 12–14. Messages are comprised of data types, identifiers, and index positions.</p><p>You’d also note messages are composed inside Services. Service is simply what this web service does. We currently have a Calculator service from lines 3-5. Calculator service comprises of a method called Add. Add takes 2 parameters as defined in <strong>Input</strong> message and emits an <strong>Output</strong> message.</p><h3>Generate code from a proto file</h3><p>You’d need a protoc compiler to generate code from proto files. If you are on Debian based system, you can use sudo apt install protobuf-compiler. If you are on any other OS, please read <a href="https://grpc.io/docs/protoc-installation/">Protocol Buffer Compiler Installation</a></p><p>I am going to use Go for this tutorial, so I’m going to install the Go plugin for the protoc compiler.</p><pre>go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28<br>go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2</pre><p>Now with everything in place, I’d issue this command from the root of the module:</p><pre>protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative calculator/calculator.proto</pre><p>If this command is successful, this would generate 2 more go files.</p><pre>tree calculator<br>calculator<br>├── calculator_grpc.pb.go<br>├── calculator.pb.go<br>└── calculator.proto</pre><pre>0 directories, 3 files</pre><p>If this is your first time with gRPC, and you look at the generated code now, you’d probably be lost.</p><p>We are going to use both files to create our server and the client. The generated code will start to make sense.</p><h3>Implement calculator server and the client</h3><p>We all know that the output generated by the protoc compiler is a stub. We need to use that stub as a guide to implementing/writing our client and the server code. The stub work as a guideline for us.</p><p>Right now, the generated code lives inside calculator package in <strong>calculator.pb.go</strong> which mostly deals with data part (i.e. Input, Output, Operand1, Operand2, their getters etc) and <strong>calculator_grpc.pb.go</strong> which mostly deals with method implementation (i.e Add in both server and client). The first thing in both server and client code is to import this package.</p><p>I will keep referencing the proto file as we define our client/server code.</p><h3>Write gRPC calculator server</h3><p>If you look into <strong>calculator_grpc.pb.go</strong>, you’d find that there is a struct called UnimplementedCalculatorServer. This struct represents our server. Now there is a reason it is named Unimplemented. If you look at methods attached to this struct, you&#39;d see a method named Add. This is the same method we defined in our proto file. Here is a refresher:</p><pre>// Adds two number<br>rpc Add(Input) returns (Output);</pre><p>What we are going to do is we are going to take this UnimplementedCalculatorServer and implement the Add method.</p><pre>// server is used to implement calculator.CalculatorServer.<br>type server struct {<br> pb.UnimplementedCalculatorServer<br>}</pre><pre>// Add implements calculator.CalculatorServer<br>func (s *server) Add(ctx context.Context, in *pb.Input) (*pb.Output, error) {<br> log.Printf(&quot;Received: %v %v&quot;, in.GetOperand1(), in.GetOperand2())<br> result := in.GetOperand1() + in.GetOperand2()<br> return &amp;pb.Output{Result: result}, nil<br>}</pre><p>Pay attention to the signature of the method. We are taking Input in form of *pb.Input and returning Output in form of *pb.Output. This is very the same as we declared in the proto file.</p><p>The Add implementation is incomplete without Add logic. On line 26 we are using GetOperand1 and GetOperand2 which is available from the <strong>calculator.pb.go</strong> file. At last, we use the Output struct to return the result.</p><p>Implementing the method is not enough, we also need to start the gRPC server and start listening.</p><pre>func main() {<br> flag.Parse()<br> lis, err := net.Listen(&quot;tcp&quot;, fmt.Sprintf(&quot;:%d&quot;, *port))<br> if err != nil {<br>  log.Fatalf(&quot;failed to listen: %v&quot;, err)<br> }<br> s := grpc.NewServer()<br> pb.RegisterCalculatorServer(s, &amp;server{})<br> log.Printf(&quot;server listening at %v&quot;, lis.Addr())<br> if err := s.Serve(lis); err != nil {<br>  log.Fatalf(&quot;failed to serve: %v&quot;, err)<br> }<br>}</pre><p>On line 32 I’m starting to listen to TCP connection on a given port. grpc.NewServer() calls the internal library function to create a new gRPC server, this call returns a grpc.ServiceRegistrar object. This object is then passed to RegisterCalculatorServer along with our implemented methods.</p><p>The whole code looks like this:</p><pre>package main</pre><pre>import (<br> &quot;context&quot;<br> &quot;flag&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net&quot;</pre><pre>pb &quot;github.com/santosh/example/calculator&quot;<br> &quot;google.golang.org/grpc&quot;<br>)</pre><pre>var (<br> port = flag.Int(&quot;port&quot;, 50051, &quot;The server port&quot;)<br>)</pre><pre>// server is used to implement calculator.CalculatorServer.<br>type server struct {<br> pb.UnimplementedCalculatorServer<br>}</pre><pre>// Add implements calculator.CalculatorServer<br>func (s *server) Add(ctx context.Context, in *pb.Input) (*pb.Output, error) {<br> log.Printf(&quot;Received: %v %v&quot;, in.GetOperand1(), in.GetOperand2())<br> result := in.GetOperand1() + in.GetOperand2()<br> return &amp;pb.Output{Result: result}, nil<br>}</pre><pre>func main() {<br> flag.Parse()<br> lis, err := net.Listen(&quot;tcp&quot;, fmt.Sprintf(&quot;:%d&quot;, *port))<br> if err != nil {<br>  log.Fatalf(&quot;failed to listen: %v&quot;, err)<br> }<br> s := grpc.NewServer()<br> pb.RegisterCalculatorServer(s, &amp;server{})<br> log.Printf(&quot;server listening at %v&quot;, lis.Addr())<br> if err := s.Serve(lis); err != nil {<br>  log.Fatalf(&quot;failed to serve: %v&quot;, err)<br> }<br>}</pre><p>In the above implementation, we have used flag the library to pass the port from the command line.</p><h3>Write gRPC calculator client</h3><p>Like we have done with server code, we’ll start by defining command line flag s.</p><pre>var (<br> addr     = flag.String(&quot;addr&quot;, &quot;localhost:50051&quot;, &quot;the address to connect to&quot;)<br> operand1 = flag.Int(&quot;op1&quot;, 2, &quot;1st operand&quot;)<br> operand2 = flag.Int(&quot;op2&quot;, 2, &quot;2nd operand&quot;)</pre><pre>operand1int32 = int32(*operand1)<br> operand2int32 = int32(*operand2)<br>)</pre><p>Line 19–20 here are kind of a hack as flag module does not have a way to accept int32 which is requirement for our Output.Result.</p><p>Next is connecting with the server part:</p><pre>// Set up a connection to the server.<br> conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))<br> if err != nil {<br>  log.Fatalf(&quot;did not connect: %v&quot;, err)<br> }<br> defer conn.Close()</pre><p>grpc.Dial takes address of the server as well as other variadic parameters. As gRPC works over HTTP2 which is by default requires TLS, we are using insecure credentials as we have not configured our server to use certificates.</p><p>On the next line, we are going to create a new gRPC client:</p><pre>c := pb.NewCalculatorClient(conn)</pre><p>In the preceding lines, we are going to invoke the Add endpoint:</p><pre>// Contact the server and print out its response.<br> ctx, cancel := context.WithTimeout(context.Background(), time.Second)<br> defer cancel()<br> r, err := c.Add(ctx, &amp;pb.Input{Operand1: operand1int32, Operand2: operand2int32})<br> if err != nil {<br>  log.Fatalf(&quot;could not add: %v&quot;, err)<br> }<br> log.Printf(&quot;Add result: %v&quot;, r.GetResult())</pre><p>The entirety of the code looks like this:</p><pre>package main</pre><pre>import (<br> &quot;context&quot;<br> &quot;flag&quot;<br> &quot;log&quot;<br> &quot;time&quot;</pre><pre>pb &quot;github.com/santosh/example/calculator&quot;<br> &quot;google.golang.org/grpc&quot;<br> &quot;google.golang.org/grpc/credentials/insecure&quot;<br>)</pre><pre>var (<br> addr     = flag.String(&quot;addr&quot;, &quot;localhost:50051&quot;, &quot;the address to connect to&quot;)<br> operand1 = flag.Int(&quot;op1&quot;, 2, &quot;1st operand&quot;)<br> operand2 = flag.Int(&quot;op2&quot;, 2, &quot;2nd operand&quot;)</pre><pre>operand1int32 = int32(*operand1)<br> operand2int32 = int32(*operand2)<br>)</pre><pre>func main() {<br> flag.Parse()<br> // Set up a connection to the server.<br> conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))<br> if err != nil {<br>  log.Fatalf(&quot;did not connect: %v&quot;, err)<br> }<br> defer conn.Close()<br> c := pb.NewCalculatorClient(conn)</pre><pre>// Contact the server and print out its response.<br> ctx, cancel := context.WithTimeout(context.Background(), time.Second)<br> defer cancel()<br> r, err := c.Add(ctx, &amp;pb.Input{Operand1: operand1int32, Operand2: operand2int32})<br> if err != nil {<br>  log.Fatalf(&quot;could not add: %v&quot;, err)<br> }<br> log.Printf(&quot;Add result: %v&quot;, r.GetResult())<br>}</pre><p>Let’s go ahead and test our service.</p><h3>Demo our server and the client</h3><p>I have recorded a gif for the demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RG93m58ZaJQxQKerfgaDXg.gif" /><figcaption><em>gRPC calculator demo</em></figcaption></figure><p>Here I have demonstrated with the default flag value, but you can override -op1 and -op2 flag to see different results.</p><h3>Conclusion</h3><p>This was merely an introduction to gRPC and protocol buffer. What I’ve found is different than a conventional REST API is the endpoints. In REST, we have a predefined endpoint to hit. Such as /calculation/add. We would then pass JSON with the first and the second operand.</p><p>This is not the case with gRPC. We get the stub files as the protoc artifact. The only communication is from there.</p><p>In this post, I have only covered the <strong>Unary</strong> service method types. I’ll leave streaming for some other time. If you’d like to read and practice more gRPC, I’d found <a href="https://dev.to/techschoolguru/series/7311">this series very helpful</a>.</p><h3>External Links</h3><ul><li><a href="https://developers.google.com/protocol-buffers/docs/proto3">Protocol Buffers Proto3 documentation</a></li><li><a href="https://grpc.io/">GRPC official Documentation</a></li><li><a href="https://stackoverflow.com/q/36517829/939986">What does multiplexing mean in HTTP/2</a></li></ul><p><em>Originally published at </em><a href="https://santoshk.dev/posts/2022/grpc-for-absolute-beginners-in-go/"><em>https://santoshk.dev</em></a><em> on May 16, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43b39a49596b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>