<?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 Pawan Kumar on Medium]]></title>
        <description><![CDATA[Stories by Pawan Kumar on Medium]]></description>
        <link>https://medium.com/@kumar16.pawan?source=rss-4dfa88ab64f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*08WanbuP1crdZuSnAcosPQ.jpeg</url>
            <title>Stories by Pawan Kumar on Medium</title>
            <link>https://medium.com/@kumar16.pawan?source=rss-4dfa88ab64f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:58:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kumar16.pawan/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[Integrating Swagger with Gin Framework in Go.]]></title>
            <link>https://medium.com/@kumar16.pawan/integrating-swagger-with-gin-framework-in-go-f8d4883f4833?source=rss-4dfa88ab64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8d4883f4833</guid>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[gin]]></category>
            <dc:creator><![CDATA[Pawan Kumar]]></dc:creator>
            <pubDate>Tue, 04 Oct 2022 17:07:42 GMT</pubDate>
            <atom:updated>2022-10-05T05:19:31.745Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT4uQwLt2AyurOGWFW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT4uQwLt2AyurOGWFW%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxT4uQwLt2AyurOGWFW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="239" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a5078a50dba78276307b93102898764/href">https://medium.com/media/6a5078a50dba78276307b93102898764/href</a></iframe><blockquote>“Documentation is a love letter that you write to your future self. “</blockquote><blockquote>— Damian Conway</blockquote><p>Documentation has always been a tedios(in my humble opinion) yet one of the most crucial task while coding. In this article, we are going to learn about integrating Swagger specification with Gin framework. We will implement <strong>JWT auth ,Request Body as Form data and JSON</strong> .Only prerequisite here is <a href="https://github.com/gin-gonic/gin">Gin Server</a>. You can refer to existing APIs on github <a href="https://github.com/lovemapa/todo-Go">here</a>.</p><p>💀 <strong>To build from source you need </strong><a href="https://golang.org/dl/"><strong>Go</strong></a><strong> (1.16 or newer).</strong></p><ol><li>Below is the existing structure before we proceeed to anything.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*YaHqL8yMwcY3HEmTsyx5cQ.png" /></figure><p>2. Let’s install some go dependencies</p><pre>go get -u github.com/swaggo/swag/cmd/swag</pre><p><a href="https://github.com/swaggo/swag"><strong>Swag</strong> </a>converts Go annotations to Swagger Documentation 2.0</p><pre>go get -u github.com/swaggo/gin-swagger<br>go get -u github.com/swaggo/files</pre><p><a href="https://github.com/swaggo/gin-swagger"><strong>gin-swagger</strong></a><strong> </strong>uses gin middleware to automatically generate RESTful API documentation with Swagger 2.0</p><p><a href="https://github.com/swaggo/files"><strong>files</strong></a><strong> </strong>generates swagger ui embedded files</p><p><strong>Its time to get our hands dirty </strong><a href="https://emojipedia.org/hacker-cat/">🐱‍💻</a></p><p>Run swag init in the project&#39;s root folder which contains the main.go file. This will parse your comments and generate the required files (docs folder and docs/docs.go).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*uFjHkq46G50j1bDOvrwvjA.png" /></figure><p>Let’s try to build and run our server using</p><pre>$ go build </pre><p>which will build and create an executable file. In my case it is TODO.exe and then run TODO.exe .</p><pre>$ .\TODO.exe</pre><p>Now navigate to <a href="http://localhost:8081/swagger/index.html">http://localhost:8081/swagger/index.html</a> to see if it is working</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_aPgCiSmjes55a7zW_Vzg.png" /></figure><p>Seems like a bit off. Lets make it work.</p><p>Import the generated docs/docs.go so that our specific configuration gets init&#39;ed in the <strong>main.go</strong>.</p><p>Also, we will add G<a href="https://github.com/swaggo/swag#general-api-info">eneral API</a> annotations in <strong>main.go</strong></p><pre>package main<br>import <br>(<br>router &quot;TODO/api/Handlers&quot;<br>&quot;fmt&quot;<br>&quot;os&quot;<br><strong>_ &quot;TODO/docs&quot; // import the docs, here TODO is my directory name</strong><br>&quot;github.com/gin-gonic/gin&quot;<br>&quot;github.com/joho/godotenv&quot;<br><strong>swaggerfiles &quot;github.com/swaggo/files&quot;<br>ginSwagger &quot;github.com/swaggo/gin-swagger&quot;</strong><br>)</pre><pre><strong>// @title TODO APIs<br>// @version 1.0<br>// @description Testing Swagger APIs.<br>// @termsOfService </strong><a href="http://swagger.io/terms/"><strong>http://swagger.io/terms/</strong></a></pre><pre><strong>// @contact.name API Support<br>// @contact.url </strong><a href="http://www.swagger.io/support"><strong>http://www.swagger.io/support</strong></a><strong><br>// @contact.email support@swagger.io</strong></pre><pre><strong>// @securityDefinitions.apiKey JWT<br>// @in header<br>// @name token</strong></pre><pre><strong>// @license.name Apache 2.0<br>// @license.url </strong><a href="http://www.apache.org/licenses/LICENSE-2.0.html"><strong>http://www.apache.org/licenses/LICENSE-2.0.html</strong></a></pre><pre><strong>// @host localhost:8081<br>// @BasePath /api/v1</strong></pre><pre><strong>// @schemes http</strong><br>func main() {</pre><pre><strong>// @schemes http</strong><br>func main() {</pre><pre>r := gin.Default()<br>r = router.Router()<br>godotenv.Load(&quot;.env&quot;)<br>port := os.Getenv(&quot;PORT&quot;)<br>fmt.Println(&quot;this is port&quot;, port)</pre><pre>// use ginSwagger middleware to serve the API docs</pre><pre><strong>r.GET(&quot;/swagger/*any&quot;, ginSwagger.WrapHandler(swaggerfiles.Handler))</strong></pre><pre>fmt.Print(&quot;Listening on port&quot;)</pre><pre>r.Run(&quot;:&quot; + port)</pre><pre>}</pre><p>👉 Please mind the spacing between annotations as it is meant to be in this way.</p><p>👉 Also,<strong> </strong>Anytime we add or update update annotation, we need to run<strong> “swag init” </strong>every time to reflect the changes<strong>.</strong> OK , now lets build and run it and check if we have progressed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYRZJPw2qweBRCcMzfZWIg.png" /></figure><p>It worked 😃.</p><p>Also, notice we have added below code for <strong>JWT</strong> authentication implentation in UI.</p><pre><strong>// @securityDefinitions.apiKey JWT<br>// @in header<br>// @name token</strong></pre><p>Now, Lets add docs to API endpoints</p><p>🚀Example 1: <strong>POST</strong> with formData for Registering a new User</p><p>We will add annotations in User Controller (api\Handlers\User\UserControllers\Controllers.go)</p><p><strong>Annotations:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*mHuTdjTpo6z-jR0aMMGHbA.png" /></figure><p>We have used @Accept as <a href="https://github.com/swaggo/swag#mime-types"><strong>mpfd</strong></a><strong> </strong>(multipart/form-data), which produces JSON and uses user Model as <a href="https://en.wikipedia.org/wiki/Data_transfer_object">DTO</a>. @Tags helps in organising APIs to a group.</p><p>You can use <strong>swag fmt </strong>to format annotations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kt6AR0cD2ufUXqXJJPn1KQ.png" /><figcaption><strong>swag fmt</strong></figcaption></figure><p><strong>User Model :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*2a0PSmzb4LIXsyAsWif_Sw.png" /></figure><p>Let’s do swag init , build and Run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E09cNWBI0Mxvqzu4JLz4FQ.png" /></figure><p>Voila 🎉, It worked.</p><p>🚀Example 2 : <strong>POST</strong> with JSON body for User login</p><p><strong>Annotations:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*yUx-RbI9sU7H0wXUi3Oxmw.png" /></figure><p>Here, we have used @Accept as JSON which produce JSON and <strong>body </strong>is used instead of formData earlier.</p><p><strong>User Login Model:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*JHAqrLRoDUFmCOSKTpCH8A.png" /></figure><p>We know the drill: swag init , build and run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvH-ttkU5tjqv6kSpfW8pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*t900BsX6FVCqvI-Iht3TJg.png" /></figure><p>Perfecto💯 !!.</p><p>Now the last one .</p><p>🚀Example 3: <strong>POST</strong> with JSON body for creating a TODO with JWT auth.</p><p>We will add annotations in TodoController (api\Handlers\Todo\TodoControllers\Controllers.go)</p><p><strong>Annotations:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*-j416E55yWxhetAsPQpJcQ.png" /></figure><p>Additionaly, we have added below code for JWT Authentication</p><pre>// @securityDefinitions.apiKey token<br>// @in header<br>// @name Authorization<br>// @Security JWT</pre><p><strong>Todo model:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*NhM6snp0DfpuizTxniU2mQ.png" /></figure><p>Take a note of key-value <strong>swaggerignore:”true”. </strong>This would help to hide those parameters which we don’t need in UI.</p><p>for the last time, 🥱 lets do👉 swag init , build and run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*jZh4XqMXAF_1nK_ktmohOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*Er8Nc8CzysAANhkyjpS4zA.png" /></figure><p>That was all 😛.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*MqFrF23-TauRLhXQQarX9Q.png" /></figure><p>Though Our end result would look like above snippet ,I hope I was able to make clear most of it with few examples. Would love to hear the feedback and improvements I can make further. You find the code repo <a href="https://github.com/lovemapa/todo-Go">here</a> on github.</p><p>References:</p><ul><li><a href="https://github.com/gin-gonic/gin">GitHub - gin-gonic/gin: Gin is a high-performance HTTP web framework written in Go. It provides a Martini-like API but with significantly better performance-up to 40 times faster-thanks to httprouter. Gin is designed for building REST APIs, web applications, and microservices.</a></li><li><a href="https://github.com/swaggo/gin-swagger">GitHub - swaggo/gin-swagger: gin middleware to automatically generate RESTful API documentation with Swagger 2.0.</a></li><li><a href="https://github.com/swaggo/swag">GitHub - swaggo/swag: Automatically generate RESTful API documentation with Swagger 2.0 for Go.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8d4883f4833" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling  live tweets from twitter in Kafka and Node]]></title>
            <link>https://medium.com/@kumar16.pawan/handling-live-tweets-from-twitter-in-kafka-and-node-7eca93e5e27a?source=rss-4dfa88ab64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eca93e5e27a</guid>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Pawan Kumar]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 11:23:58 GMT</pubDate>
            <atom:updated>2020-04-27T11:23:58.917Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling live tweets from twitter in Kafka and Node</h3><p>Well before starting, I am assuming that you are well acquainted with basics of <a href="https://kafka.apache.org/">Apache Kafka</a> like dealing with Topics, Producers ,Consumers and Consumer groups. Now, as we already know about <a href="https://kafka.apache.org/">Kafka</a> is a perfect choice for handling real-time data feeds . So I shall be using <a href="https://www.npmjs.com/package/kafka-node">Kafka-node</a>, a Node.js client for Apache Kafka to handle data streams from twitter. Besides I’ve used <a href="https://github.com/ttezel/twit">twit</a>, a Twitter API Client for node getting real time streams of tweets. Also you need to have a <a href="https://developer.twitter.com/en/apply-for-access">Twitter’s developer account</a> making it possible to access your account using credentials which probably would look something like this after setup.</p><figure><img alt="credentials in keys and tokens section of you app." src="https://cdn-images-1.medium.com/max/880/1*A91otX2cxyGBnuC_Ozh_HA.png" /><figcaption>twitter credentials</figcaption></figure><p>Make sure to run zookeeper and kafka in your command line(where Kafka is installed) using zookeeper-server-start.sh config/zookeeper.properties and kafka-server-start.sh config/server.properties respectively before running any script. Now , before creating a topic you can use command kafka-topics.sh --zookeeper 127.0.0.1:2181 --list to list down all created topics in you Kafka console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*qQ8-yIHfbx6ID6rE0ZjCOw.png" /><figcaption>All topics</figcaption></figure><p>Now I’ll create a new topic name <strong>twitterNode </strong>with the help of <a href="https://www.npmjs.com/package/kafka-node">Kafka-node</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*LWcnPFmN8L8EQS_cOUzRwQ.png" /><figcaption>Create a topic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*d0kMYejk5TWKHcMS5hRELA.png" /><figcaption>Newly added topic</figcaption></figure><p>Now, first we setup <a href="https://www.npmjs.com/package/twit">twit</a> for getting live streams of tweets .All the credentials would be available to you once you setup developer’s account.You can scroll to <a href="https://developer.twitter.com/en/docs">Twitter docs</a> for getting more insights into REST and streaming APIs like applying filters for getting tweets from a particular language or preferred geo locations. Here I’m using Real Madrid’s(being a Madridsta 😉 ) handle to get their live tweets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*v-kNogTNodDsZ6gARLyAqA.png" /><figcaption>script for getting live stream of tweets</figcaption></figure><p>And you would get all the live tweets from that handle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgmibDQaxe1pLhAoTQmk6Q.png" /><figcaption>streams of tweets</figcaption></figure><p>As a live example you can see I just made a tweet through my twitter account and you could that tweet in my console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*s7Af69YYm7euob0W4a3e5Q.png" /><figcaption>Tweet from account</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9t867k-IesH4elVLQrdMw.png" /><figcaption>console output of tweet</figcaption></figure><p>Now I’ll just modify my above twitter handling file to add new Producer which would publish tweets to the Kafka cluster coming from twitter handle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*gx8zmy8BeKrPyA-5Ds07ug.png" /><figcaption>Producer</figcaption></figure><p>Below is the result of data being published with <strong>twitterNode</strong> as name of topic and 0,1 and 2 being the partitions and their corresponding values as their offset ,i.e the last index up-to which data has been committed .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mRc1ZNVuFnQ_YBX20FkDg.png" /><figcaption>Producer Output</figcaption></figure><p>Now coming to the last step, listening to topic as Consumers. Since Consumer generally listens as group to a particular topic, so below is the consumer-group script for listening to <strong>twitterNode </strong>topic.Here I’m using the group name <strong>my_first_app </strong>in groupId .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*s4JQafLAJOfT_X036VuZMw.png" /><figcaption>topic consumer</figcaption></figure><p>and this would how exactly your topic look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_ZOoKzfqJLneUoDBzNFWw.png" /><figcaption>consumer output</figcaption></figure><p>You can keep track of the particular group listening to various topics in kafka-cli as kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe — group my_first_app which probably would give you result something like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FzyAx6WduihOgF6wbtWDKQ.png" /><figcaption>Inspecting group</figcaption></figure><p>So this was all about practical implementation of Kafka basics. Feel free to ask and add your views what more I can add to this . Find the git repository <a href="https://github.com/lovemapa/node-kafka/tree/master">here</a>.</p><p><strong>References :</strong></p><ul><li><a href="https://kafka.apache.org/">Apache Kafka</a></li><li><a href="https://www.npmjs.com/package/kafka-node">kafka-node</a></li><li><a href="https://github.com/ttezel/twit">ttezel/twit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eca93e5e27a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload File and serve in Go]]></title>
            <link>https://medium.com/@kumar16.pawan/upload-file-and-serve-in-go-c12d88b3e519?source=rss-4dfa88ab64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12d88b3e519</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Pawan Kumar]]></dc:creator>
            <pubDate>Sat, 28 Dec 2019 13:57:24 GMT</pubDate>
            <atom:updated>2019-12-28T14:34:19.615Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last <a href="https://medium.com/@kumar16.pawan/creating-a-crud-application-using-go-and-mongodb-cc077ce2d0e">tutorial</a>, we learned about doing basic CRUD operations in Go and MongoDB. Here comes another basic yet joyous task, <strong>dealing with static files.</strong> Uploading and serving files in Go is less or zero cumbersome. Here, I’ll be uploading the file into a directory named static and save the path into MongoDB database and retrieve it later. So let’s keep <strong>GO</strong>ing….</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXcAa52ejGuNqdb5SFQ%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXcAa52ejGuNqdb5SFQ%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FXcAa52ejGuNqdb5SFQ%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc0b820e5410a87906da11ecbf7e75d4/href">https://medium.com/media/fc0b820e5410a87906da11ecbf7e75d4/href</a></iframe><p>So, the basic file structure would be</p><pre> main.go                     # main file containing route for upload<br> db.go                       #for Database connection<br> controllers.go              #Handeler for route<br> <strong>static           #</strong>Directory where files will be uploaded and served</pre><p>I’ve already explained <strong>main.go</strong> and <strong>db.go </strong><a href="https://medium.com/@kumar16.pawan/creating-a-crud-application-using-go-and-mongodb-cc077ce2d0e">here</a> except for a new thing in <strong>main.go</strong> file.</p><p>route.PathPrefix(“/”).Handler(http.FileServer(http.Dir(“./static”)))</p><p>http.FileServer()returns a handler that serves HTTP requests with the contents of the file system rooted at the root. Since we will not be using root but our current working directory, so http.Dir(&quot;./static&quot;) will be fed as the argument to http.FileServer() , where <strong>.</strong><em>(dot)</em> represents the root of the current working directory and after that <strong>static </strong>directory will be used to serve files. In the end, any file that is to be served (<em>it has to be present in </em><strong>static</strong><em> folder first</em>) over server will be there at <a href="http://localhost:8000/">http://localhost:8000</a>/ . example if there is an image name myProfilePic.png in static directory, then it will be served as <a href="http://localhost:8000/">http://localhost:8000</a>/myProfilePic.png .</p><p><strong>main.go</strong></p><pre>package main<br>import (<br>&quot;github.com/gorilla/mux&quot;<br>&quot;log&quot;<br>&quot;net/http&quot;<br>)</pre><pre>func main() {<br>route := mux.NewRouter()<br>s := route.PathPrefix(&quot;/api&quot;).Subrouter() //Base Path<br><strong>route.PathPrefix(&quot;/&quot;).Handler(http.FileServer(http.Dir(&quot;./static&quot;)))</strong>//For serving static files </pre><pre><br>//ROUTES</pre><pre>s.HandleFunc(&quot;/uploadFile&quot;, uploadFile).Methods(&quot;POST&quot;)  //upload           //File handler</pre><pre>s.HandleFunc(&quot;/getAllUsers&quot;, getAllUsers).Methods(&quot;GET&quot;) //display //All list of users</pre><pre><br>log.Print(&quot;Server Connected 🚀 &quot;)log.Fatal(http.ListenAndServe(&quot;:8000&quot;, route)) // Run Server</pre><pre>}</pre><p>Now coming to uploading part in <strong>controllers.go</strong></p><pre>func <strong>createProfile</strong>(w http.ResponseWriter, r *http.Request) {</pre><pre>w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>r.ParseMultipartForm(10 &lt;&lt; 20)</pre><pre>file, _, err := r.FormFile(&quot;file&quot;)<br>if err != nil {<br>fmt.Println(&quot;error while getting the File&quot;)<br>fmt.Println(err)<br>return<br>}</pre><pre>defer file.Close()</pre><pre>tempFile, err := ioutil.TempFile(&quot;static&quot;, &quot;upload-*.png&quot;)</pre><pre>if err != nil {<br>fmt.Println(err)<br>}</pre><pre>defer tempFile.Close()</pre><pre>fileBytes, err := ioutil.ReadAll(file)<br>if err != nil {<br>fmt.Println(err)<br>}</pre><pre>tempFile.Write(fileBytes)</pre><pre>person := user{<br>Name:       r.FormValue(&quot;name&quot;),<br>City:       r.FormValue(&quot;city&quot;),<br>ProfilePic: &quot;/&quot; + path.Base(tempFile.Name()),<br>}</pre><pre><br>insertResult, err := userCollection.InsertOne(context.TODO(), person)</pre><pre>if err != nil {<br>log.Fatal(err)<br>}</pre><pre>json.NewEncoder(w).Encode(insertResult.InsertedID) // return the //mongodb ID of generated document</pre><pre>}</pre><p>Let’s go one by one in <strong>createProfile() </strong>function. r.ParseMultipartForm()parses a request body as multipart/form-data, up to a total of mentioned bytes(here 10&lt;&lt;20) as argument are stored in memory, with the remainder stored on disk in temporary files.</p><p>r.FormFile(“file”) returns the first file provided by the key <strong>file </strong>from the request. defer file.Close() makes sure it is closed in the end after all the nearby functions are called.</p><p>ioutil.TempFile(“static”, “uploadFile-*.png”) creates a new temporary file in the directory <strong>static</strong> , opens the file for reading and writing. The <em>filename</em> is generated by taking the <em>pattern</em> provided as the second argument and adding a random string to the end. If pattern includes a “*”, the random string replaces the last “*”.Here output file will be like uploadFile-643278432.png. Again don’t forget to close it using defer tempFile.Close() .</p><p>Now, read all the contents of file which we got above, using ioutil.ReadAll(file) which will return bytes of that file . Now write down all the bytes into newly created tempFile using tempFile.Write(fileBytes) .</p><p>Create a user struct from request <strong>r</strong> and save it into person</p><pre>person := user{<br>Name:       r.FormValue(&quot;name&quot;),           <br>City:       r.FormValue(&quot;city&quot;),<br>ProfilePic: &quot;/&quot; + path.Base(tempFile.Name()),<br>}</pre><p>As tempFile.Name() contains the file name with concatenated directory(here it isstatic/uploadFile-643278432.png), so static is slashed using path.Base() .</p><p>In the end, collection can be saved from person as</p><p>insertResult, err := userCollection.InsertOne(context.TODO(), person) which will yield MongoDB _id from insertResult.InsertedID .</p><p>Run the application using <strong>go run *.go</strong></p><p>Here are some screenshots for the sake of clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*eXDkVkRoEeL2E8j_xJJ2LQ.png" /><figcaption>Request</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*uh-VVuDS09LFA0kPEdyNDA.png" /></figure><p>Hit getAllUsers <a href="https://github.com/lovemapa/go">API</a> and you will get the list of all users. Click image link by field <strong>profilepic </strong>and there go <strong>GO</strong>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5a251TLs4I0UF5lbwe6LIw.png" /></figure><p>You can find the whole code <a href="https://github.com/lovemapa/go-static">here</a>. Feel free to share your thoughts and valuable advice. Thanks for reading.</p><p><strong>References :</strong></p><ul><li><a href="https://github.com/gorilla/mux">https://github.com/gorilla/mux</a></li><li><a href="https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial">https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial</a></li><li><a href="https://godoc.org/go.mongodb.org/mongo-driver/mongo">https://godoc.org/go.mongodb.org/mongo-driver/mongo</a></li><li><a href="https://godoc.org/io/ioutil">https://godoc.org/io/ioutil</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12d88b3e519" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a CRUD application using GO and MongoDB]]></title>
            <link>https://medium.com/@kumar16.pawan/creating-a-crud-application-using-go-and-mongodb-cc077ce2d0e?source=rss-4dfa88ab64f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc077ce2d0e</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Pawan Kumar]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 23:28:06 GMT</pubDate>
            <atom:updated>2019-12-23T23:28:06.818Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fdr6toZX3D1O8%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fdr6toZX3D1O8%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fdr6toZX3D1O8%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d36e8ce4a13b364011c44fe8503f4c0/href">https://medium.com/media/9d36e8ce4a13b364011c44fe8503f4c0/href</a></iframe><p>Recently I was going through some videos on <a href="http://www.youtube.com/">www.youtube.com</a> and a link popped up as ”HOT UPCOMING LANGUAGES in 2020&quot;. Out of curiosity I opened it and got to know about GO. After reading about it, I decided to give it a try and Voila!!!. It was FUN :).</p><p>So I tried to demonstrate CRUD operations through this post, keeping it as simple as I can. So let&#39;s GO…</p><p>The first step would be to install the MongoDB driver using <strong>go get</strong> i.e</p><pre>go get github.com/mongodb/mongo-go-driver</pre><p>There might be a warning displaying something likepackage go.mongodb.org/mongo-driver: no Go files in (...). Don’t <strong>PANIC.</strong> This is expected output from go get.</p><p>I’ve created three files named main.go ,db.go and controllers.go. in /src folder under the directory mongoCRUD. So the structure looks like</p><pre>src/<br>    <a href="https://github.com/golang/example/">m</a>ongoCRUD/<br>        main.go                      # main file containing routes<br>	db.go                        #for Database connection<br>        controllers.go               #Handelers for routes</pre><p>Let’s go to the anatomy of files one by one, starting with <strong>main.go</strong></p><pre>package main</pre><pre>import (<br>&quot;github.com/gorilla/mux&quot;<br>&quot;log&quot;<br>&quot;net/http&quot;<br>)</pre><pre><br>func main() {<br>route := mux.NewRouter()</pre><pre>s := route.PathPrefix(&quot;/api&quot;).Subrouter() <strong>//Base Path</strong></pre><pre><strong>//Routes</strong></pre><pre>s.HandleFunc(&quot;/createProfile&quot;, createProfile).Methods(&quot;POST&quot;)<br>s.HandleFunc(&quot;/getAllUsers&quot;, getAllUsers).Methods(&quot;GET&quot;)<br>s.HandleFunc(&quot;/getUserProfile&quot;, getUserProfile).Methods(&quot;POST&quot;)<br>s.HandleFunc(&quot;/updateProfile&quot;, updateProfile).Methods(&quot;PUT&quot;)<br>s.HandleFunc(&quot;/deleteProfile/{id}&quot;, deleteProfile).Methods(&quot;DELETE&quot;)</pre><pre>log.Fatal(http.ListenAndServe(&quot;:8000&quot;, s)) <strong>// Run Server</strong><br>}</pre><p>I’ve used packagegorilla/mux which implements a request router and dispatcher for matching incoming requests to their respective handlers.HandleFunc registers a new route with a matcher for the URL path.</p><p><strong>db.go</strong></p><pre>package main</pre><pre>import (<br>&quot;context&quot;<br>&quot;fmt&quot;<br>&quot;log&quot;<br>&quot;go.mongodb.org/mongo-driver/mongo&quot;<br>&quot;go.mongodb.org/mongo-driver/mongo/options&quot;<br>)</pre><pre>func db() *mongo.Client {</pre><pre>clientOptions := options.Client().ApplyURI(&quot;mongodb://localhost:27017&quot;)// Connect to //MongoDB</pre><pre>client, err := mongo.Connect(context.TODO(), clientOptions)<br>if err != nil {<br>log.Fatal(err)<br>}</pre><pre><strong>// Check the connection</strong><br>err = client.Ping(context.TODO(), nil)</pre><pre>if err != nil {<br>log.Fatal(err)<br>}</pre><pre>fmt.Println(&quot;Connected to MongoDB!&quot;)<br>return client<br>}</pre><p>A connection is set up using mongo.Connect(context.TODO(), clientOptions) .Package context tells about like deadlines, cancellation signals.Further TODO() is used when it’s unclear which Context to use or it is not available.clientOptions contains options like pool size,authentication.In the end client returns *mongo.Client which will be used to access different collections.</p><p>Now we will go through each function of <strong>controllers.go</strong> <strong>.</strong>But before that, we will be accessing users collection as</p><p>var userCollection = db().Database(&quot;goTest&quot;).Collection(&quot;users&quot;) where db() contains the *mongo.Client from <strong>db.go</strong>. Besides we have used user struct to store information.</p><pre>type user struct{<br>Name string `json:&quot;name&quot;`<br>City string `json:&quot;city&quot;`<strong><br></strong>Age int `json:&quot;age&quot;`<br>}</pre><p><strong>CREATE</strong></p><pre>func createProfile(w http.ResponseWriter, r *http.Request) {w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;) // for adding       //Content-type</pre><pre>var person user</pre><pre>err := json.NewDecoder(r.Body).Decode(&amp;person) // storing in person   //variable of type <strong>user</strong></pre><pre>if err != nil {</pre><pre>fmt.Print(err)</pre><pre>}</pre><pre>insertResult, err := userCollection.InsertOne(context.TODO(),person)<br>if err != nil {<br>log.Fatal(err)<br>}</pre><pre>json.NewEncoder(w).Encode(insertResult.InsertedID) // return the //mongodb ID of generated document</pre><pre>}</pre><p><strong>READ</strong></p><pre>func getUserProfile(w http.ResponseWriter, r *http.Request) {</pre><pre>w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)</pre><pre>var body user</pre><pre>e := json.NewDecoder(r.Body).Decode(&amp;body)</pre><pre>if e != nil {<br>fmt.Print(e)<br>}</pre><pre>var result primitive.M //  an unordered representation of a BSON //document which is a Map</pre><pre>err := userCollection.FindOne(context.TODO(), bson.D{{&quot;name&quot;, body.Name}}).Decode(&amp;result)</pre><pre>if err != nil {<br>fmt.Println(err)<br>}<br>json.NewEncoder(w).Encode(result) // returns a Map containing //mongodb document<br>}</pre><p><strong>UPDATE</strong></p><pre>func updateProfile(w http.ResponseWriter, r *http.Request) {<br>w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)</pre><pre>type updateBody struct {<br>Name string `json:&quot;name&quot;` //value that has to be matched<br>City string `json:&quot;city&quot;` // value that has to be modified<br>}</pre><pre>var body updateBody<br>e := json.NewDecoder(r.Body).Decode(&amp;body)<br>if e != nil {<br>fmt.Print(e)<br>}</pre><pre>filter := bson.D{{&quot;name&quot;, body.Name}} // converting value to BSON after := options.After         // for returning updated document    </pre><pre>returnOpt := options.FindOneAndUpdateOptions{<br>ReturnDocument: &amp;after,<br>}</pre><pre>update := bson.D{{&quot;$set&quot;, bson.D{{&quot;city&quot;, body.City}}}}</pre><pre>updateResult := userCollection.FindOneAndUpdate(context.TODO(), filter, update, &amp;returnOpt)</pre><pre>var result primitive.M</pre><pre>_ = updateResult.Decode(&amp;result)</pre><pre>json.NewEncoder(w).Encode(result)<br>}</pre><p><strong>DELETE</strong></p><pre>func deleteProfile(w http.ResponseWriter, r *http.Request) {</pre><pre>w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>params := mux.Vars(r)[&quot;id&quot;] //get Parameter value as string</pre><pre>_id, err := primitive.ObjectIDFromHex(params) // convert params to //mongodb Hex ID</pre><pre>if err != nil {<br>fmt.Printf(err.Error())<br>}</pre><pre>opts := options.Delete().SetCollation(&amp;options.Collation{}) // to //specify language-specific rules for string comparison, such as //rules for lettercase</pre><pre>res, err := userCollection.DeleteOne(context.TODO(), bson.D{{&quot;_id&quot;, _id}}, opts)</pre><pre>if err != nil {<br>log.Fatal(err)<br>}</pre><pre>json.NewEncoder(w).Encode(res.DeletedCount) // return number of //documents deleted</pre><pre>}</pre><p>In the end run the application using<strong> go run *go .</strong></p><p><a href="https://github.com/lovemapa/go">Here</a> is git repository for the whole code. I hope this tutorial was useful to get some insights into CRUD application.</p><p>Get <a href="https://www.getpostman.com/collections/b1faa791265334374516">here</a> POSTMAN import link for APIs.</p><p><strong>References :</strong></p><ul><li><a href="https://github.com/gorilla/mux">https://github.com/gorilla/mux</a></li><li><a href="https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial">https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial</a></li><li><a href="https://godoc.org/go.mongodb.org/mongo-driver/mongo">https://godoc.org/go.mongodb.org/mongo-driver/mongo</a></li></ul><p><strong>PS:</strong> <em>This is my first article. So any changes or suggests are heartly welcomed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc077ce2d0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>