<?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 Rakesh Mirji on Medium]]></title>
        <description><![CDATA[Stories by Rakesh Mirji on Medium]]></description>
        <link>https://medium.com/@rakeshmirji?source=rss-69e2e9cd9e2d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2ThwKbQzUfro9gBx</url>
            <title>Stories by Rakesh Mirji on Medium</title>
            <link>https://medium.com/@rakeshmirji?source=rss-69e2e9cd9e2d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:53:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rakeshmirji/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[Creating S3 Folders Automatically with GO]]></title>
            <link>https://medium.com/@rakeshmirji/creating-s3-folders-automatically-with-go-b4fb1ad54f6b?source=rss-69e2e9cd9e2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4fb1ad54f6b</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[file-upload]]></category>
            <dc:creator><![CDATA[Rakesh Mirji]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 13:20:44 GMT</pubDate>
            <atom:updated>2025-01-25T13:20:44.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*uAFLf0x6JYnAj8kkaL2-HQ.png" /></figure><p>As I develop backend in Go, I deal with uploading Images and PDFs frequently. Let us proceed further with the assumption that we are using Amazon’s S3 bucket to store files. One might think that after creating am AWS S3 bucket we just need to create folders to store Files and Images. That is right, to some extent.</p><p>Imagine a you are required to stored images and their report cards of all the student in a university, which contains multiple colleges and schools.</p><p>In situations like these data need to be organized and accessible, so we create a folder objects for every college and school which come under that university, easy right ?</p><blockquote>note : <br>&gt; you may refer my article on retrieving and storing files from below.</blockquote><p><a href="https://medium.com/@rakeshmirji/using-go-channels-to-retrieve-images-and-pdfs-from-aws-s3-storage-a5c2acf10187">Using Go Channels to Retrieve Images and PDFs from AWS S3 Storage.</a></p><p>To some extent this is correct and would work correctly, but what to do when a new Education Institution is created under that university ?</p><p>What you can do now is manually create another folder in your AWS S3 bucket and name the folder as the new institution’s code, so we can store files from that institution inside it.</p><p>Implementing this we are required to create a new folder in AWS S3 bucket every time a new institute is added.</p><p>The drawback to this approach is if we try to store files before creating the folder or in a situation when someone forgets to create a folder due to human error. The alternative that I thaught to overcome this is we create a folder using code when a new institution is added to the database.</p><p>In python we can use BOTO 3 to achieve this, simillary I will demonstrate the same using Go.</p><p>If you decide to store your files, images in AWS S3 storage here are some<br>pre-requisite libraries in GO:<br>github.com/aws/aws-sdk-go/aws/credentials<br>github.com/aws/aws-sdk-go/aws/config <br>github.com/aws/aws-sdk-go/service/s3</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> <br> &quot;github.com/aws/aws-sdk-go-v2/config&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/credentials&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/service/s3&quot;<br>)<br><br>func main() {<br>  name := &quot;school01&quot;<br>  err := createS3Folder(name)<br>  if err != nil {<br>     log.Fatalf(&quot;Error! : &quot;,err)<br>  }<br>}<br><br>func createS3Folder(folderName string){<br> accessKey := &quot;AKID&quot;<br> secretKey := &quot;SECRETkEYID&quot;<br> region := &quot;YOUR_REGION&quot;<br><br> cfg, err := config.LoadDefaultConfig(context.TODO(),<br>  config.WithRegion(region),<br>  config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, &quot;&quot;)),<br> )<br> if err != nil {<br>  log.Fatalf(&quot;unable to load SDK config, %v&quot;)<br>  return err<br> }<br><br> s3Client := s3.NewFromConfig(cfg)<br><br> bucket := &quot;YOUR_BUCKEY_NAME&quot;<br> folder := folderName + &quot;/&quot;<br><br> _, err = s3Client.PutObject(context.TODO(), &amp;s3.PutObjectInput{<br>  Bucket: &amp;bucket,<br>  Key:    &amp;folder,<br>  Body:   nil, // No content for folder, it&#39;s just a placeholder<br> })<br> if err != nil {<br>  log.Println(&quot;unable to upload empty object, %v&quot;)<br>  return err<br> }<br><br> fmt.Println(&quot;Folder created successfully!&quot;)<br> return err<br>}</pre><p>As you can see I use createS3Folder() function to create a new folder dynamically as soon as a institution is added.</p><p>Here is how this code snippet works</p><ul><li>We load AWS SDK config with credentials<br> cfg, err := config.LoadDefaultConfig() , using this config we create a S3 service client s3Client :=s3.NewFromConfig(cfg)</li><li>After the S3 client is created we upload an empty object file to simulate the folder as key with a PutObject API.</li><li>If This is successfully executed then the new Object folder is created in S3, we can then upload files to this folder.</li></ul><h4>conclusion</h4><p>In this article, I demonstrated how to dynamically create folders in an AWS S3 bucket using the Go SDK. While S3 doesn’t have a traditional folder structure, we can simulate it by uploading objects with specific prefixes (ending with a /), which AWS S3 interprets as folders.</p><p>With this method, you can now efficiently manage folder-like structures in your S3 buckets, keeping your data organized and accessible with just a few lines of Go code. You can also use go routine’s incase you want to add multiple folders simultanouslty.</p><p>Thanks for reading, and feel free to connect with me on Linkedin : <a href="https://www.linkedin.com/in/rakesh-mirji-26339b1b1/">https://www.linkedin.com/in/rakesh-mirji-26339b1b1/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4fb1ad54f6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Go Channels to Retrieve Images and PDFs from AWS S3 Storage.]]></title>
            <link>https://medium.com/@rakeshmirji/using-go-channels-to-retrieve-images-and-pdfs-from-aws-s3-storage-a5c2acf10187?source=rss-69e2e9cd9e2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c2acf10187</guid>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goroutines]]></category>
            <dc:creator><![CDATA[Rakesh Mirji]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 15:29:06 GMT</pubDate>
            <atom:updated>2025-01-16T15:29:06.979Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Backend developer, I have to upload images &amp; files to store them, but due to limited space in my online server, I could either resize them or store then whole in a cloud storage like Amazon S3, BLOB storage or Google storage. I choose Amazon S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTpgR1QtveHY-q1yNIWxiw.png" /><figcaption><strong>Looping with a Channel</strong></figcaption></figure><p>Before using Go channels to retrieve image we first need to understand pre-signed url.</p><p>If you decide to store your files, images in AWS S3 storage here are some<br>pre-requisite libraries in GO:<br>github.com/aws/aws-sdk-go/aws<br>github.com/aws/aws-sdk-go/aws/credentials<br>github.com/aws/aws-sdk-go/aws/session<br>github.com/aws/aws-sdk-go/service/s3</p><blockquote><strong>Key Features of a Pre-signed URL:</strong></blockquote><blockquote><strong>Temporary Access</strong>: The URL is valid for a specified period of time and automatically expires once that time is reached.</blockquote><blockquote><strong>Access Control</strong>: Only the user who generates the pre-signed URL can determine the permissions (e.g., whether it’s for <strong>reading</strong>, <strong>writing</strong>, or <strong>downloading</strong>) for the URL.</blockquote><blockquote><strong>No Direct Authentication</strong>: It allows access to a private resource without needing to share AWS credentials or make the object public.</blockquote><blockquote><strong>upload files</strong>: It can be used to allow someone to upload a file to an S3 bucket without exposing your AWS credentials.</blockquote><p>In summary <strong>pre-signed URL</strong> is a URL that allows temporary access to an object stored in a private cloud storage service, such as <strong>Amazon S3</strong>. This URL is generated by the owner of the object (typically with credentials) and can be used by others to access the object without needing to directly share credentials or make the object public.</p><p>Prior to uploading, we first generate a presigned url which is used to upload the file to S3 bucket, To generate this the owner uses S3 region, bucket name, access key, secret access key. These can be accessed through the .env file.</p><p>In the code snippet below I take s3 folder name, filename, method &amp; mime type as parameter and return string and error.</p><p><strong>Generate a pre-signed url:<br></strong>Before we upload the file, we require a pre-signed url. First we need a instance of a service client which requires region, access key, secret access key. after a instance of a service client svc := s3.New(session) is generated. Here we call the below function in the code below S3PresignURL(&quot;demo&quot;,&quot;image.png&quot;,&quot;POST&quot;,&quot;image/png&quot;) . We use PutObjectRequest() to prepare an HTTP request to upload an object to an S3 bucket. It could be a pre-signed URL or an object used to configure the upload.</p><blockquote>note: <br>. mime type for pdf is application/pdf &amp; for images it is image/png or image/jpg , so on.<br>. We set the pre-signed url expiry as 15 minutes.</blockquote><p>Next we use a HTTP put Method to put the file in s3 bucket using pre-signed URL.</p><pre>import(<br> &quot;github.com/aws/aws-sdk-go/aws&quot;<br> &quot;github.com/aws/aws-sdk-go/aws/credentials&quot;<br> &quot;github.com/aws/aws-sdk-go/aws/session&quot;<br> &quot;github.com/aws/aws-sdk-go/service/s3&quot;<br>)<br><br>func S3PresignURL(bucketType, filename, method, mimeType string) (string, error) {<br>region := &quot;YOUR_REGION_NAME&quot;<br>bucket := &quot;YOUR_BUCKET_NAME&quot;<br>accessKeyID := &quot;AKID&quot;<br>secretAccessKeyID := &quot;SECRET&quot;<br><br>session := session.Must(session.NewSessionWithOptions(session.Options{<br>  Config: aws.Config{<br>   Region: aws.String(region),<br>   Credentials: credentials.NewCredentials(&amp;credentials.StaticProvider{<br>    Value: credentials.Value{<br>     AccessKeyID:     accessKeyID,<br>     SecretAccessKey: secretAccessKeyID,<br>    },<br>   }),<br>  },<br> }))<br> fmt.Println(&quot;----&quot;,region)<br><br> svc := s3.New(session)<br> pr, _ := svc.GetObjectRequest(&amp;s3.GetObjectInput{<br>  Bucket: aws.String(bucket),<br>  Key:    aws.String(bucketType + &quot;/&quot; + filename),<br> })<br>             <br> if method == &quot;POST&quot; {<br>  pr, _ = svc.PutObjectRequest(&amp;s3.PutObjectInput{<br>   Bucket: aws.String(bucket),<br>   Key:    aws.String(bucketType + &quot;/&quot; + filename),<br>   ContentType: &amp;mimeType,<br>  })<br> }<br><br> if method == &quot;GET&quot; {<br>  // Create the pre-signed url with an expiry<br>  // todo read from property<br>  url, err := pr.Presign(2 * time.Hour)<br>  if err != nil {<br>   fmt.Println(region+&quot; Failed to generate a pre-signed url: &quot;, err)<br>   log.Println(&quot;Failed to generate a pre-signed url: &quot;, err)<br>   return &quot;&quot;, err<br>  }<br><br>  return url, nil<br> }<br> // Create the pre-signed url with an expiry<br> url, err := pr.Presign(15 * time.Minute)<br> if err != nil {<br>  fmt.Println(region+&quot; Failed to generate a pre-signed url: &quot;, err)<br>  log.Println(&quot;Failed to generate a pre-signed url: &quot;, err)<br>  return &quot;&quot;, err<br> }<br><br> return url, nil<br>}</pre><p><strong>Retrieve (download) an object from an S3 bucket:</strong> <br>Now that we learnt how to upload the file, we proceed to retrieve the file and display/download whenever needed. To achieve this we use the above code S3PresignURL(&quot;demo&quot;,&quot;image.png&quot;,&quot;GET&quot;,&quot;image/png&quot;). In this version we use generate a pre-signed URL with a much longer expiry than the one we used for pre-signed url, in case we needed to dispaly this url.</p><p><strong>channels to retrieve files</strong></p><p>Now that we know how to upload and retrieve a file, we introduce channels and go routines to retrieve muliples files. <strong>channels</strong> allows goroutines (concurrent functions) to communicate with each other and synchronize their execution.</p><p>We create an unbuffered channel that will carry array of struct File <br>channel := make(chan int). The go keyword launches a new goroutine to send a value into the channel. The main goroutine waits for the value to be received from the channel with &lt;-channel. This is carried out in a loop where in every iteration we append the retrieved value in fileData.</p><pre>type File struct {<br> Id         int       `json:&quot;id,omitempty&quot;`<br> Name       string    `json:&quot;name,omitempty&quot;`<br> Alias      string    `json:&quot;alias,omitempty&quot;`<br> CreatedOn  time.Time `json:&quot;-&quot;`<br> File       *string   `json:&quot;file,omitempty&quot;`<br>}<br><br>func GetFiles(files []*File)([]*File){<br>  var fileData []*File<br>  channel := make(chan File)<br>  for _,file := range files {<br>    go RetrieveFromAWS(*file, channel)<br>  }<br>  for range files{<br>    file := &lt;-channel<br>    fileData = append(fileData, &amp;file)<br>  }<br>  return fileData<br>}</pre><p>Declare a struct File that stores filename, file which can be accessed through an API. Use S3PresignURL() function from above to retrieve file from Amazon S3 and send the url to the main goroutine. This way multiple files can be retrieved concurrently by calling the go routine in a loop.</p><pre>func RetrieveFromAWS(file File, channel chan&lt;- File){<br> mimeType := &quot;&quot;<br> atype := &quot;demo&quot;<br> key := file.Name<br><br> if StringMatchLastWord(key,&quot;.pdf&quot;){<br>  mimeType = &quot;application/pdf&quot;<br> } else if StringMatchLastWord(key,&quot;.png&quot;){<br>   mimeType = &quot;image/png&quot;<br> } else if (StringMatchLastWord(key,&quot;.jpeg&quot;) || StringMatchLastWord(key,&quot;.jpg&quot;)) {<br>   mimeType = &quot;image/jpeg&quot;<br> } else{<br>  channel &lt;- file<br>  return<br> }<br> if atype == &quot;&quot; || key == &quot;&quot; {<br>  channel &lt;- file<br>  return<br> }<br> url, err := S3PresignURL(atype, key, &quot;GET&quot;,mimeType)<br> if err != nil {<br>  log.Println(err.Error())<br>  channel &lt;- file<br>  return  <br> }<br> // log.Println(url)<br> file.File = &amp;url<br> channel &lt;- file<br>}<br><br>func StringMatchLastWord(str,sub string)bool{<br>    match, _ := regexp.MatchString(sub+&quot;$&quot;, str)<br> return match<br>}</pre><p><strong>Conclusion</strong></p><p>Go is well-suited for applications where simplicity, performance, and concurrency are essential. Whether you are building a small script to interact with APIs or performing concurrent tasks like downloading files, Go’s channels and goroutines make handling multiple tasks straightforward and efficient.</p><p>Thanks for reading, and feel free to connect with me on Linkedin : <a href="https://www.linkedin.com/in/rakesh-mirji-26339b1b1/">https://www.linkedin.com/in/rakesh-mirji-26339b1b1/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c2acf10187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Transfer Between Excel, Database, and CSV with Pandas]]></title>
            <link>https://medium.com/@rakeshmirji/data-transfer-between-excel-database-and-csv-with-pandas-b5eacd6df568?source=rss-69e2e9cd9e2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5eacd6df568</guid>
            <category><![CDATA[data-management]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rakesh Mirji]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 18:09:16 GMT</pubDate>
            <atom:updated>2025-01-05T18:09:16.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U0uE1uBT2tqPGlWilYWiQ.png" /><figcaption>pandas for DataScience</figcaption></figure><p>In Python, when working with data manipulation or analysis panda library is one of the most popular library out there.</p><p>I will now illustrate the use of panda to transfer data between Excel, Database, and CSV. These are some methods I use when dealign with data manipulation as a backend developer.</p><p><strong>Inserting Data from Excel to Database</strong></p><p>Firstly using read_excel() method from pandas we read the excel sheet, then we connect to database and create a cursor object. Lastly we write a SQL query to insert the data that we retrived from the excel.</p><p>We extract data from excel as name = df.loc[i,’subject’].strip()</p><pre>import pandas as pd <br>import mysql.connector<br><br>df = pd.read_excel(&quot;/path/to/file/school_data.xlsx&quot;,sheet_name=&quot;class1&quot;)<br><br>#establishing the connection<br>conn = mysql.connector.connect(<br>   user=&#39;root&#39;, password=&#39;root&#39;, host=&#39;127.0.0.1&#39;,port=&#39;3306&#39;, database=&#39;schoolDatabase&#39;<br>)<br><br>#Creating a cursor object using the cursor() method<br>cursor = conn.cursor()<br><br># Preparing SQL query to INSERT a record into the database.<br>for i in range(len(df)):<br>    name = df.loc[i,&#39;subject&#39;].strip()<br>    sql = f&quot;&quot;&quot;INSERT INTO class(<br>    name, created_on)<br>    VALUES (<br>    &quot;{name}&quot;,<br>    NOW())&quot;&quot;&quot;<br><br>    try:<br>        # Executing the SQL command<br>        cursor.execute(sql)<br>        # Commit your changes in the database<br>        conn.commit()<br><br>    except Exception as err:<br>        print(err)<br>        # Rolling back in case of error<br>        conn.rollback()<br><br># Closing the connection<br>conn.close()</pre><p><strong>Saving Data from Database to Excel</strong></p><p>Here I has a database dump file and had to retrieve a particular data in a excel. I first import sql dump file in MySQL database.</p><p>As I have shown above program, use a SQL query to retrive data in dataframe. Lastly stored the dataFrame to an excel file using df.to_excel() method and close the connection. In the end a new excel with named hospital_data.xlsx is created.</p><pre>import pandas as pd <br>import mysql.connector<br><br>#establishing the connection<br>conn = mysql.connector.connect(<br>   user=&#39;root&#39;, password=&#39;root&#39;, host=&#39;127.0.0.1&#39;,port=&#39;3306&#39;, database=&#39;hospitalDatabase&#39;<br>)<br><br># Create the query to fetch data<br>query = &quot;SELECT * FROM hospital&quot;<br><br># Read data from the MySQL database into a pandas DataFrame<br>df = pd.read_sql(query, conn)<br><br># Write the DataFrame to an Excel file<br>df.to_excel(&#39;hospital_data.xlsx&#39;, sheet_name=&#39;Hospital Data&#39;, index=False, engine=&#39;openpyxl&#39;)<br><br># Close the MySQL connection<br>conn.close()</pre><p><strong>Saving Data from Database to CSV</strong></p><p>Just as above we establish the connection to MySLQ server followed by creating a cursor object, then execute a SQL query to retrieve desired data. In my case I’am retrieving patient appointment data from a hospital database. Next we sort the data in a data structure . Lastly we store the data in a CSV file.</p><pre>with open(csv_file, mode=&#39;w&#39;, newline=&#39;&#39;) as file:<br>    writer = csv.DictWriter(file, fieldnames=data[0].keys())<br>    writer.writeheader()  # Write the header<br>    writer.writerows(data)  # Write the data rows</pre><p>we use csv library to create header &amp; rows and write using csv.DictWriter() method.</p><pre>import pandas as pd <br>import mysql.connector<br>import csv<br><br>#establishing the connection<br>conn = mysql.connector.connect(<br>   user=&#39;root&#39;, password=&#39;root&#39;, host=&#39;127.0.0.1&#39;,port=&#39;3306&#39;, database=&#39;hospitalDatabase&#39;<br>)<br>#Creating a cursor object using the cursor() method<br>cursor = conn.cursor()<br>patients=[]<br><br>try:<br>    # Executing the SQL command<br>    cursor.execute(&quot;&quot;&quot;SELECT DISTINCT name, phone, created_on FROM doctor_appointment WHERE hospital_id = 6 AND DATE(created_on) &gt; DATE(&quot;2024-10-15&quot;) ORDER BY created_on DESC LIMIT 500;&quot;&quot;&quot;)<br>    patients = cursor.fetchall()<br>except Exception as err:<br>    print(err)<br><br># Closing the connection<br>conn.close()<br><br>data=[]<br><br>for patient in patients:<br>    data.append({&#39;name&#39;: str(patient[0]), &#39;phone&#39;: str(patient[1])})<br><br># Specify the CSV file name<br>csv_file = &#39;data.csv&#39;<br><br># Write data to the CSV file<br>with open(csv_file, mode=&#39;w&#39;, newline=&#39;&#39;) as file:<br>    writer = csv.DictWriter(file, fieldnames=data[0].keys())<br>    writer.writeheader()  # Write the header<br>    writer.writerows(data)  # Write the data rows<br><br>print(f&quot;Data saved to {csv_file}&quot;)</pre><p>In conclusion, Pandas provides a efficient way to manage data transfers between Excel, databases, and CSV files. Whether you’re automating data insertion, extraction, or export, leveraging Pandas simplifies these tasks and significantly enhances productivity. Personally, With just a few lines of code, I can streamline my workflow and focus on what matters most.</p><p>ie:- analyzing and using data effectively.</p><p><strong>Drawbacks of pandas</strong></p><p>There are quiet a few criticisms towards padas too:</p><ul><li>Pandas can require 5 to 10 times as much memory as the size of the underlying data, and the entire dataset must be loaded in RAM.</li><li>The library does not optimize query plans or support parallel computing across multiple cores.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5eacd6df568" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Image Upload, Resize, and Encoding in Go: A Comprehensive Guide to File Handling]]></title>
            <link>https://medium.com/@rakeshmirji/mastering-image-upload-resize-and-encoding-in-go-a-comprehensive-guide-to-file-handling-d5ed344a09d5?source=rss-69e2e9cd9e2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ed344a09d5</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[resize-images]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[file-handling]]></category>
            <dc:creator><![CDATA[Rakesh Mirji]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 11:13:49 GMT</pubDate>
            <atom:updated>2024-12-30T11:13:49.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86VX7aCZWHxKLYP4kKzDYg.png" /></figure><p>Go is a powerhouse when it comes to <strong>file handling</strong>, thanks to its:</p><ul><li><strong>Robust standard library</strong>.</li><li><strong>Third-party libraries</strong> like resize and pdf that make your job easier.</li><li><strong>Performance</strong> that ensures scalability, even with large file uploads and processing.</li></ul><p><strong>Backend development</strong> often involves handling file uploads. Whether it’s images or PDFs and ensuring they are processed, resized, and stored correctly. If you’re working with Go (Golang) and need a straightforward approach to managing file uploads and image resizing, I’ve written a detailed guide just for you.</p><p>If you are working with images/PDF in Go and want to handle file uploads, resize them, and encode them into different formats, then you’ve come to the right place. Go is very efficient for backend development, and in this guide, I’ll show you how to handle image uploads, resize them, and then save them in different formats. Let’s dive into it!</p><p>In this section, I explain how to:</p><ul><li>Upload images via multipart form data using Go’s http package.</li><li>Decode and resize images to your preferred dimensions using the popular nfnt/resize library.</li><li>Save the resized image in different formats (JPEG, PNG) on the server, and even remove old images to prevent duplication.</li></ul><p><strong>Prerequisites</strong></p><p>Before you start, make sure you have Go installed on your machine, we’ll need a couple of libraries to work with images, so make sure you install them.</p><pre>go get github.com/nfnt/resize</pre><p>I will cover file and image resizing separately, first lets get started with Image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*VPqCWjUpTJWwtYlugLY7mQ.png" /></figure><p>First, I upload an image file from the frontend using multipart form data through REST APIs, With the help of request header, we access the form to retrieve the file data.</p><p>We first open the image, and then we decode it.</p><pre>// Decode the image<br> img, _, err := image.Decode(file)<br> if err != nil {<br>  return &quot;Unable to decode image&quot;, err<br> }</pre><p>Then, we use the github.com/nfnt/resize package to resize the image to the desired resolution, for example 800 pixels</p><pre>// Resize the image to a width of 800 while maintaining aspect ratio<br> resizedImg := resize.Resize(800, 0, img, resize.Lanczos3)</pre><p>Finally, we save the newly resized image to the file system. If you want this to be the updated file, we first remove the previous file and then save the new one.</p><pre>// Save the resized image to the new file<br> switch handler.Header.Get(&quot;Content-Type&quot;) {<br> case &quot;image/jpeg&quot;:<br>  err = jpeg.Encode(out, resizedImg, nil)<br> case &quot;image/png&quot;:<br>  err = png.Encode(out, resizedImg)<br> default:<br>  return &quot;Unsupported file format&quot;, err<br> }</pre><p>Here, we will explore how to store both single and multiple files.</p><p><strong>Single Image File: </strong>How to upload and save a single image, with automatic renaming using uuid to prevent duplication.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br> &quot;strings&quot;<br> &quot;image&quot;<br> &quot;image/jpeg&quot;<br> &quot;image/png&quot;<br> &quot;github.com/nfnt/resize&quot;<br> &quot;path/filepath&quot;<br>)<br><br>func ResizeAndSaveImage(data ...interface{})(string,error){<br> r := data[0].(*http.Request)<br> fieldName := data[1].(string)<br> path := data[2].(string)<br><br> file, handler, err := r.FormFile(fieldName)<br> if err != nil {<br>  if err.Error() == &quot;http: no such file&quot; {<br>   return &quot;&quot;, nil<br>  }<br>  return &quot;Unable to retrieve file&quot;, err<br> }<br> defer file.Close()<br> <br>// To Prevent Duplication we use uuid as image name<br> ext := strings.Split(handler.Filename,&quot;.&quot;)<br> uuid := uuid.New().String()+&quot;.&quot;+ext[len(ext)-1]<br> <br> // Decode the image<br> img, _, err := image.Decode(file)<br> if err != nil {<br>  return &quot;Unable to decode image&quot;, err<br> }<br><br> // Resize the image to a width of 800 while maintaining aspect ratio<br> resizedImg := resize.Resize(800, 0, img, resize.Lanczos3)<br><br> // Create a new file on the server with a new name<br> _ = os.MkdirAll(path, os.ModePerm)<br> newFileName := filepath.Join(path, uuid) <br> out, err := os.Create(newFileName)<br> if err != nil {<br>  return &quot;Unable to create file&quot;, err<br> }<br> defer out.Close()<br><br> // Save the resized image to the new file<br> switch handler.Header.Get(&quot;Content-Type&quot;) {<br> case &quot;image/jpeg&quot;:<br>  err = jpeg.Encode(out, resizedImg, nil)<br> case &quot;image/png&quot;:<br>  err = png.Encode(out, resizedImg)<br> default:<br>  return &quot;Unsupported file format&quot;, err<br> }<br> if err != nil {<br>  return &quot;Unable to save image&quot;, err<br> }<br><br> if len(data) &gt; 3 &amp;&amp; data[3].(string) != &quot;&quot; {<br>  oldPath := data[3].(string)<br>  err := os.Remove(oldPath)<br>  if err != nil {<br>   return &quot;failed to delete file&quot;, err<br>  }<br>  fmt.Println(&quot;old image deleted.&quot;)<br> }<br><br> return newFileName, err<br>}</pre><p><strong>Multiple Image Files: </strong>Efficiently handle multiple image uploads in one go and save each resized image on the server.</p><pre>package main<br><br>import (<br>&quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br> &quot;strings&quot;<br> &quot;image&quot;<br> &quot;image/jpeg&quot;<br> &quot;image/png&quot;<br> &quot;github.com/nfnt/resize&quot;<br> &quot;path/filepath&quot;<br>)<br><br>func ResizeAndSaveMultipleImages(data ...interface{})([]string,error){<br> r := data[0].(*http.Request)<br> fieldName := data[1].(string)<br> path := data[2].(string)<br> var fileNames []string<br><br> files := r.MultipartForm.File[fieldName]<br> if len(files) == 0 {<br>  return nil, nil<br> }<br> for _, handler := range files {<br>  file, err := handler.Open()<br>  if err != nil {<br>   return nil, err<br>  }<br>  defer file.Close()<br>  <br>  // To Prevent Duplication we use uuid as image name<br>  ext := strings.Split(handler.Filename,&quot;.&quot;)<br>  uuid := uuid.New().String()+&quot;.&quot;+ext[len(ext)-1]<br>  <br>  // Decode the image<br>  img, _, err := image.Decode(file)<br>  if err != nil {<br>   return nil, err<br>  }<br><br>  // Resize the image to a width of 800 while maintaining aspect ratio<br>  resizedImg := resize.Resize(800, 0, img, resize.Lanczos3)<br><br>  // Create a new file on the server with a new name<br>  _ = os.MkdirAll(path, os.ModePerm)<br>  newFileName := filepath.Join(path, uuid) <br>  out, err := os.Create(newFileName)<br>  if err != nil {<br>   return nil, err<br>  }<br>  fileNames = append(fileNames,newFileName)<br>  defer out.Close()<br><br>  // Save the resized image to the new file<br>  switch handler.Header.Get(&quot;Content-Type&quot;) {<br>  case &quot;image/jpeg&quot;:<br>   err = jpeg.Encode(out, resizedImg, nil)<br>  case &quot;image/png&quot;:<br>   err = png.Encode(out, resizedImg)<br>  default:<br>   return nil, err<br>  }<br>  if err != nil {<br>   return nil, err<br>  }<br><br>  if len(data) &gt; 3 &amp;&amp; data[3].(string) != &quot;&quot; {<br>   oldPath := data[3].(string)<br>   err := os.Remove(oldPath)<br>   if err != nil {<br>    return nil, err<br>   }<br>   fmt.Println(&quot;old image deleted.&quot;)<br>  }<br> }<br> return fileNames, nil<br>}</pre><p>Both functions return the file name after execution.</p><p><strong>Encode Image to Base64</strong></p><p>If we want to send the stored image through an API, we encode the image in Base64 format using encoding/base64 package and send it as a string, along with any other relevant information.</p><pre>package main<br><br>import(<br> &quot;strings&quot;<br> &quot;io/ioutil&quot;<br> &quot;encoding/base64&quot;<br>)<br><br>func EncodeImageToBase64(path string)(string,string,error){<br> var base64Image string <br> var ext string<br> var err error<br><br> imageArr := strings.Split(path,&quot;.&quot;)<br> ext = imageArr[len(imageArr)-1]<br><br> img, err := ioutil.ReadFile(path)<br> if err != nil {<br>  return base64Image,ext,err<br> }<br> base64Image = base64.StdEncoding.EncodeToString(img)<br> return base64Image,ext,err<br>}</pre><p><strong>PDF Upload</strong></p><p>Now using io package, I upload the PDF file from the frontend using multipart form data through REST APIs. With the help of the request header, we access the form to retrieve the file data, just like we did with the image upload mentioned above.</p><p>Go also offers excellent support for file handling, including PDFs. I demonstrated how to:</p><ul><li>Upload PDF files using multipart form data.</li><li>Retrieve the file, save it, and even read the number of pages in the PDF using the pdf library.</li><li>we get the page count using read.NumPage() method.</li></ul><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;io&quot;<br> &quot;strings&quot;<br> &quot;github.com/dslipak/pdf&quot;<br> &quot;os&quot;<br> &quot;path/filepath&quot;<br>)<br><br>func SaveFile(r *http.Request, data ...interface{})(int,string,error){<br> var count int<br> var fullPath string<br> var err error<br><br>fileType, dir := data[0].(string), data[1].(string)<br> <br> f, h, err := r.FormFile(fileType)<br> if err != nil {<br>  fmt.Println(err.Error())<br>  if strings.Contains(err.Error(), &quot;no such file&quot;){<br>   return count,fullPath,nil<br>  }<br>  return count,fullPath,err<br> }<br><br> defer f.Close()<br><br> fileName := h.Filename<br><br> if fileType == &quot;file&quot;{<br>  fileName = data[2].(string)<br> }<br> <br> path := filepath.Join(&quot;.&quot;, dir)<br> _ = os.MkdirAll(path, os.ModePerm)<br> fullPath = filepath.Join(path, fileName)<br><br> file, err := os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE, os.ModePerm)<br> if err != nil {<br>  return count,fullPath,err<br> }<br><br> defer file.Close()<br> // Copy the file to the destination path<br> _, err = io.Copy(file, f)<br> if err != nil {<br>  return count,fullPath,err<br> }<br><br> read, err := pdf.Open(fullPath)<br> if err != nil {<br>  fmt.Println(err.Error())<br>  return count,fullPath,nil<br> }<br><br> count = read.NumPage()<br> return count,fullPath,err<br>}</pre><p>This function return page count &amp; file path after execution.</p><p><strong>Conclusion:</strong></p><p>In this guide, we’ve explored how to efficiently handle image and PDF uploads in Go, with a focus on resizing images, encoding them to Base64, and processing PDFs. Go’s simplicity, combined with powerful libraries like nfnt/resize and pdf, makes it an excellent choice for backend development when dealing with file uploads and processing tasks.</p><p>Whether you’re building a photo-sharing app, a document management system, or just need a reliable solution for file handling, Go provides a streamlined approach that ensures <strong>performance</strong>, <strong>scalability</strong>, and <strong>ease of use. </strong>The Go community continues to grow, and I encourage you to keep experimenting and learning.</p><p>If you have any questions or suggestions, feel free to leave them in the comments. Let’s continue to share knowledge and improve together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ed344a09d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time in Go: Overview with Examples]]></title>
            <link>https://medium.com/@rakeshmirji/time-in-go-overview-with-examples-ebb9e30cdb45?source=rss-69e2e9cd9e2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebb9e30cdb45</guid>
            <category><![CDATA[package]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Rakesh Mirji]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 18:00:21 GMT</pubDate>
            <atom:updated>2024-12-24T18:00:21.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="go" src="https://cdn-images-1.medium.com/max/690/1*o56Q0Sc0Q7bhZESyxcodvw.png" /></figure><p>In Go (Golang), handling time is done through the time package, which provides functionality for working with durations, dates, and timestamps. Here&#39;s a comprehensive breakdown of how to work with time in Go:</p><ol><li>Getting Current Time</li><li>Formatting Time</li><li>Parsing Time</li><li>Time Arthmatic</li><li>Time Zone</li><li>Time Duration</li><li>Working with WeekDay, Year, Month</li></ol><p><strong>Getting Current Time</strong></p><p>To get the current date and time, you use time.Now():</p><pre>package main<br><br>import(<br>  &quot;fmt&quot;<br>  &quot;time&quot;<br>)<br><br>func main(){<br>   currentTime := time.Now()<br>   fmt.Println(&quot;Current Time:&quot;, currentTime)<br> }<br></pre><p>This prints current time in local time zone.</p><p><strong>Formatting Time</strong></p><p>The time.Format() function allows you to format a time.Time object as a string in a specific format. The Go time format is based on a reference date: &quot;Mon Jan 2 15:04:05 2006&quot;.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> currentTime := time.Now()<br> // Format the time using a custom layout<br> fmt.Println(&quot;Formatted Time:&quot;, currentTime.Format(&quot;2006-01-02 15:04:05&quot;))<br> fmt.Println(&quot;Formatted Time:&quot;, currentTime.Format(&quot;2006-01-02&quot;))<br> fmt.Println(&quot;Formatted Time:&quot;, currentTime.Format(&quot;2006/01/02 03:04 PM&quot;))<br> fmt.Println(&quot;Formatted Time:&quot;, currentTime.Format(&quot;02-01-2006 15:04&quot;))<br>}</pre><p>Here inside the .Format() method we add the formatting pattern</p><p><strong>Parsing Time</strong></p><p>To parse a string into a time.Time, you use the time.Parse() function, which also follows the reference date format.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> timeStr := &quot;2024-12-24 13:45:00&quot;<br> layout := &quot;2006-01-02 15:04:05&quot;<br> parsedTime, err := time.Parse(layout, timeStr)<br> if err != nil {<br>  fmt.Println(&quot;Error parsing time:&quot;, err)<br>  return<br> }<br> fmt.Println(&quot;Parsed Time:&quot;, parsedTime)<br>}</pre><p>Here as seen above the reference date is the same as for Formatting Time</p><p><strong>Time Arthmatic</strong></p><p>You can perform arithmetic on time.Time values using Add(), Sub(), and AddDate() methods. You can add or subtract time.Duration values (or years, months, and days).</p><ul><li><strong>Add</strong>: Adds a time.Duration to a time.Time.</li><li><strong>Sub</strong>: Subtracts two time.Time values and returns a time.Duration.</li><li><strong>AddDate</strong>: Adds a specified number of years, months, and days to a time.</li></ul><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> now := time.Now()<br> // Add 10 days to the current time<br> futureTime := now.Add(10 * 24 * time.Hour)<br> fmt.Println(&quot;Future Time:&quot;, futureTime)<br><br> // Subtract 5 days from current time<br> pastTime := now.Add(-5 * 24 * time.Hour)<br> fmt.Println(&quot;Past Time:&quot;, pastTime)<br><br> // Add 1 year, 2 months, and 3 days<br> updatedTime := now.AddDate(1, 2, 3)<br> fmt.Println(&quot;Updated Time:&quot;, updatedTime)  <br>}</pre><p><strong>Time Zone</strong></p><p>Go provides a time.Location type for working with different time zones.</p><p>You can get the current time in UTC or local time, or convert between time zones:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> // Get the current time in UTC<br> utcTime := time.Now().UTC()<br> fmt.Println(&quot;UTC Time:&quot;, utcTime)<br><br> // Get the current time in local time<br> localTime := time.Now()<br> fmt.Println(&quot;Local Time:&quot;, localTime)<br><br> // Convert between time zones<br> loc, err := time.LoadLocation(&quot;Asia/Kolkata&quot;)<br> if err != nil {<br>  fmt.Println(&quot;Error loading location:&quot;, err)<br>  return<br> }<br><br> India := localTime.In(loc)<br> fmt.Println(&quot;Time in India:&quot;, India)<br>}</pre><p><strong>Time Duration</strong></p><p>A time.Duration represents a duration of time. It can be created using time constants like time.Second, time.Minute, etc. You can add or subtract durations to time.Time values.</p><p>Example of creating and using a time.Duration:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> duration := 3 * time.Hour // 3 hours<br><br> // Adding duration to the current time<br> futureTime := time.Now().Add(duration)<br> fmt.Println(&quot;Time after 3 hours:&quot;, futureTime)<br><br> // Subtracting duration from the current time<br> pastTime := time.Now().Add(-duration)<br> fmt.Println(&quot;Time 3 hours ago:&quot;, pastTime)<br>}</pre><p><strong>Working with WeekDay, Year, Month</strong></p><p>You can easily get the weekday, month, and year from a time.Time object.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> currentTime := time.Now()<br><br> // Get the weekday<br> fmt.Println(&quot;Weekday:&quot;, currentTime.Weekday())<br><br> // Get the month<br> fmt.Println(&quot;Month:&quot;, currentTime.Month())<br><br> // Get the year<br> fmt.Println(&quot;Year:&quot;, currentTime.Year())<br>}</pre><p><strong>Conclusion</strong></p><p>In Go, handling time is both efficient and flexible, thanks to the comprehensive features provided by the time package. Whether you&#39;re fetching the current time with time.Now(), performing time calculations, formatting dates, or managing durations, Go simplifies working with time. The ability to handle different time zones, set up timers, or even compare timestamps makes Go a powerful tool for building time-sensitive applications. By mastering these concepts, you can write robust and time-aware code that meets the demands of any project, from small utilities to large-scale systems, all while keeping your approach clear and precise.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebb9e30cdb45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting with GO]]></title>
            <link>https://medium.com/@rakeshmirji/starting-with-go-eb82e0894431?source=rss-69e2e9cd9e2d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb82e0894431</guid>
            <category><![CDATA[go-programing-l]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Rakesh Mirji]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 18:12:37 GMT</pubDate>
            <atom:updated>2023-11-08T11:28:08.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zud-L6m4Dd3Ikf_4vcZcKQ.jpeg" /></figure><p>Go is a statically typed language like C, Java, C++ and has its own syntax, control flow statements, basic data types, call-by-value parameters, pointers, methods, interfaces, OOP’s ..so on as in any other language’s.</p><p>In this post I will discuss about the following</p><p>Here’s a basic go syntax,</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main(){<br>  fmt.Println(&quot;Hello World!&quot;)<br>}</pre><p>In the above example the package main is a standalone execution program, and the package fmt is used for printing formated output and scanning input.</p><p>main will call upon the functions in another packages to do much of the work, such as fmt.Println() which is a output function in fmt package.</p><h4><strong>1) Variable Declaration in GO :</strong></h4><p>In GO we can declare variables in the following ways,</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main(){<br>  var a = &quot;Hello Anil :-)&quot;<br>  fmt.Println(a)<br><br>  var b,c = 1,2<br>  fmt.Println(b,c)<br><br>  var d = true<br>  fmt.Println(d)<br><br>  var e int<br>  fmt.Println(e)<br><br>  f := &quot;Coder&quot;<br>  fmt.Println(f)<br>}</pre><p>In the above code we can see that,</p><p>&gt; var declares one or more variables.</p><p>&gt; we can declare multiple variables at once.</p><p>&gt; Go will infer the type of initialized variables.</p><p>&gt; Variables declared without a corresponding initialization are <em>zero-valued</em>. For example, the zero value for an int is 0.</p><p>&gt; In case of var we must initialize the variable just after declaration.</p><p>The := syntax is shorthand for declaring and initializing a variable, e.g. for var f string = &quot;apple&quot; can alse be declared as f := apple.</p><p>&gt; Unlike normal var shorthand declaration must initialize the variable just after the declaration.</p><p>&gt; In shorthand there is <strong>no need to mention the type of the variable</strong>..</p><p>&gt; Short Declaration operator can also be used to declare multiple variables of the <strong>same type or different types </strong>in the single declaration.</p><h4>2) Constants in GO:</h4><p>GO supports constant for character, string, boolean, numeric values. A const stratement can appear anywhere a variable can</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>const s string = &quot;constant&quot;<br><br>func main(){<br>  fmt.Println(s)<br><br>  const(<br>   AbsoluteZero float64 = -273.15<br>   FeezingC = 0<br>   BoilingC float64 = 100<br>  )<br><br>fmt.Println(AbsoluteZero,BoilingC)<br><br>fmt.Println(int64(FeezingC))<br>}</pre><p>In the above code we learn how to declare a const variable.</p><p>&gt; A numeric constant has no type until it’s given one, such as by an explicit conversion.</p><p>&gt; A number can be given a type by using it in a context that requires one</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb82e0894431" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>