<?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 Nikhil Shrestha on Medium]]></title>
        <description><![CDATA[Stories by Nikhil Shrestha on Medium]]></description>
        <link>https://medium.com/@shrestha.nikhil01?source=rss-754829880a27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NWVghWTe9Ij8RsAj</url>
            <title>Stories by Nikhil Shrestha on Medium</title>
            <link>https://medium.com/@shrestha.nikhil01?source=rss-754829880a27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:43:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shrestha.nikhil01/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[Facebook Authentication with Go]]></title>
            <link>https://articles.readytowork.jp/facebook-authentication-with-go-2d7872815b3a?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d7872815b3a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 09:42:13 GMT</pubDate>
            <atom:updated>2024-01-07T09:42:13.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_QOPWhTl3-4TYFcTxDDcQ.png" /></figure><p>In this article, we will walk through the process of integrating Facebook login with the Go programming language.</p><p><strong>First, we need to set up for Facebook Developer.</strong></p><p>▹ <strong>Create a Facebook Developer Account:</strong></p><p>If you don’t already have one, go to the <a href="https://developers.facebook.com/"><em>Facebook Developer Portal</em></a>, sign in with your Facebook account, and follow the steps to create a developer account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lzBQQnCFVbdFsLBTKwvEKA.png" /></figure><p>After login, you’ll be redirected to the registration page. Choose accordingly to complete the registration process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6ZXqpMNdr8gyhK8thujnQ.png" /></figure><p>▹ <strong>Create a New App:</strong></p><p>Once logged in, go to the Facebook Developer Dashboard. Then, click on the “Create App” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eagdXigJWRXZitjweJZuGw.png" /></figure><p>Screen 1:</p><p>You may select according to your needs. However, you can also select “Other” if you are not sure at the moment and want to explore later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntFl1Uj2O5JFLrTQoC-S8w.png" /></figure><p>Screen 2:</p><p>If you are not sure about the app type, you can select “None”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntFl1Uj2O5JFLrTQoC-S8w.png" /></figure><p>Screen 3:</p><p>Enter a name for your app (here I have used the name, “Test App”). Enter your contact email. And then, click on “Create app”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3hKflnKGh1QmS1ygm2HXw.png" /></figure><p>▹ <strong>Add Facebook Login to Your App:</strong></p><p>In the app’s dashboard, under the section “Add a Product”, click on “Set up” in the “Facebook Login” card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uyv4ycxRI90iIBvbOBj0Q.png" /></figure><p>Then, you’ll be redirected to next section to select your platform. However, you can skip this and select the “Settings” instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4S3PL04Ai1sHb0kD-5t7A.png" /></figure><p>▹ <strong>Configure OAuth Settings:</strong></p><p>Here add a URL to which Facebook will redirect after a successful login. Since I am currently testing locally, I have added the URL address accordingly. Then, click on the “Save changes” button in the bottom right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aw96fSEnNIXFtc_52InaYQ.png" /></figure><p>There are also other Facebook Login settings you can explore as per your app requirements.</p><p>Next, we can start our coding section.</p><p>Install the required packages:<br>You’ll need the <a href="http://golang.org/x/oauth2">http://golang.org/x/oauth2</a> package for OAuth 2.0.</p><p>Let’s set our oauthConfig variable first. This is an OAuth2 configuration with Facebook as the identity provider.</p><pre>var(<br>  oauthConfig := &amp;oauth2.Config{<br>  		ClientID:     &quot;APP_ID&quot;,<br>  		ClientSecret: &quot;APP_SECRET&quot;,<br>  		RedirectURL:  &quot;http://localhost:8080/callback&quot;,<br>  		Scopes:       []string{&quot;email&quot;},<br>		Endpoint:     facebook.Endpoint,<br>	}<br>)</pre><p>We can get the APP_ID and APP_SECRET from our dashboard in the <a href="https://developers.facebook.com/"><em>Facebook Developer Portal</em></a>.</p><p>Go to “App settings” and inside the “Basic” section you’ll find the required keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4rqGMqpC3QnXJD2bD8e4LQ.png" /></figure><p>Now, let’s look at our functions:</p><p><strong>HandleHome()</strong></p><pre>func HandleHome(w http.ResponseWriter, r *http.Request) {<br>	w.Write([]byte(`&lt;a href=&quot;/login&quot;&gt;Login with Facebook&lt;/a&gt;`))<br>}</pre><p>This handler displays a link to initiate the Facebook login process.</p><p><strong>HandleLogin()</strong></p><pre>func HandleLogin(w http.ResponseWriter, r *http.Request) {<br>	url := oauthConfig.AuthCodeURL(&quot;state&quot;)<br>	http.Redirect(w, r, url, http.StatusTemporaryRedirect)<br>}</pre><p>This handler generates the URL for initiating the OAuth2 flow and redirects the user to the provider’s login page, i.e., Facebook in this case.</p><p><strong>HandleCallback()</strong></p><pre>func HandleCallback(w http.ResponseWriter, r *http.Request) {<br>	code := r.URL.Query().Get(&quot;code&quot;)<br>	oauthConfig := AuthConfig()<br>	token, err := oauthConfig.Exchange(r.Context(), code)<br>	if err != nil {<br>		http.Error(w, err.Error(), http.StatusInternalServerError)<br>		return<br>	}<br><br>	client := oauthConfig.Client(context.Background(), token)<br>	resp, err := client.Get(&quot;https://graph.facebook.com/v13.0/me?fields=name&quot;)<br>	if err != nil {<br>		http.Error(w, err.Error(), http.StatusInternalServerError)<br>		return<br>	}<br>	defer resp.Body.Close()<br><br>	var userInfo struct {<br>		Name string `json:&quot;name&quot;`<br>	}<br><br>	if err := json.NewDecoder(resp.Body).Decode(&amp;userInfo); err != nil {<br>		http.Error(w, err.Error(), http.StatusInternalServerError)<br>		return<br>	}<br><br>	fmt.Fprintf(w, &quot;Welcome, %s!&quot;, userInfo.Name)<br>}</pre><p>This handler retrieves the authorization code from the query parameter and exchanges it for an access token. Then, it requests the respective OAuth provider’s API using the token to fetch the name of the user. Finally, the response received from the API is decoded to get the name of the logged-in user.</p><p><strong>main()</strong></p><pre>func main() {<br>	http.HandleFunc(&quot;/&quot;, HandleHome)<br>	http.HandleFunc(&quot;/login&quot;, HandleLogin)<br>	http.HandleFunc(&quot;/callback&quot;, HandleCallback)<br>	http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p>The main function handles the route for the different handlers.</p><p><strong>Summary</strong></p><p>In a nutshell, when a user visits the home route, they are provided with a link to initiate the Facebook login process. Upon clicking this link, the user is redirected to the Facebook login page, and after successful login, Facebook redirects the user back to the “/callback” route with an authorization code. The authorization code is exchanged for an access token to access the information related to the user.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d7872815b3a" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/facebook-authentication-with-go-2d7872815b3a">Facebook Authentication with Go</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating nil value with GORM (Mapping using Reflect)]]></title>
            <link>https://articles.readytowork.jp/updating-nil-value-with-gorm-mapping-using-reflect-212cec203822?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/212cec203822</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[reflections]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[maps]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 03:46:48 GMT</pubDate>
            <atom:updated>2023-10-11T03:46:48.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBFY1Tyudk1cobZTkOUJhA.png" /></figure><p>When you are a backend developer, you have to work with APIs and databases. At the core level, we are one way or the other working to create CRUD APIs. If you are working in the Go programming language with GORM, then you might have come up with an issue in updating with nil values.</p><p>For example, this is a struct you’d like to use</p><pre>type GeneralInfo struct {<br> Name    string `json:&quot;name&quot;`<br> Age     int   `json:&quot;age&quot;`<br> Address string `json:&quot;address&quot;`<br> Occupation *string `json:&quot;occupation&quot;`<br>}</pre><p>and the existing data in your database looks something like the following:</p><pre>Name: &quot;Bond&quot;<br>Age: 30<br>Address: &quot;New york&quot;<br>Occupation: &quot;Agent&quot;</pre><p>However, now you want to update this data with the following:</p><pre>updateInfo := GeneralInfo{<br>     Name:&quot;Bond&quot;,<br>     Age:35,<br>     Address:&quot;California&quot;,<br>     Occupation:nil,<br>}</pre><p>Using GORM, we will use a line of code to update our database:</p><pre>db.Model(GeneralInfo{}).Where(“name = ?”, &quot;Bond&quot;).Updates(&amp;updateInfo)</pre><p>After running the query, you may check your database. You will find that the values for age and address were updated, but it was not the same case for the occupation. This is because when updating a struct in GORM using the Updates method, default values are ignored. So what if we want to set default values, like nil, 0 and &quot;&quot; ?</p><p>The solution would be to define the exact columns to update or use a map.</p><p>Normally, we use mapping to solve this issue. For the case mentioned in the above part of this article, the mapping would look as follows:</p><pre>db.Model(GeneralInfo{}).Where(“name = ?”, &quot;Bond&quot;).Updates(map[string]interface{}{<br> &quot;name&quot;: updateInfo.Name,<br> &quot;address&quot;: updateInfo.Age,<br> &quot;age&quot;: updateInfo.Address,<br> &quot;occupation&quot;: updateInfo.Occupation,<br>})</pre><p>This updates all the values including the nil. However, if you are working in a large system or structs with a huge number of fields, mapping can be fiddly.</p><p>We can overcome this by using the reflect package in the Go language. Reflect implements run-time reflection, allowing to manipulation of objects into arbitrary types.</p><p>Here, let’s write a function to map a struct:</p><pre>// ToMap takes in an interface{} and converts it into a map[string]interface{} representation.<br>func ToMap(data interface{}) map[string]interface{} {<br> result := make(map[string]interface{})<br> reflectValue := reflect.ValueOf(data)<br> reflectType := reflect.TypeOf(data)<br><br> for i := 0; i &lt; reflectValue.NumField(); i++ {<br>  fieldValue := reflectValue.Field(i)<br>  fieldType := reflectType.Field(i)<br><br>  if fieldValue.Kind() != reflect.Struct {<br>   result[fieldType.Name] = fieldValue.Interface()<br>  }<br><br>  if fieldValue.Kind() == reflect.Struct {<br>   nestedFields := ToMap(fieldValue.Interface())<br>   for nestedKey, nestedValue := range nestedFields {<br>    result[nestedKey] = nestedValue<br>   }<br>  }<br> }<br> return result<br>}</pre><p>Breaking down the function ToMap :</p><pre>result := make(map[string]interface{})<br> reflectValue := reflect.ValueOf(data)<br> reflectType := reflect.TypeOf(data)</pre><p>We have initialized a map interface as result. Along with it, we have also initialized reflectValue and reflectType which represent the reflected value and type of passed interface respectively.</p><pre>for i := 0; i &lt; reflectValue.NumField(); i++ {<br>  fieldValue := reflectValue.Field(i)<br>  fieldType := reflectType.Field(i)<br><br>  if fieldValue.Kind() != reflect.Struct {<br>   result[fieldType.Name] = fieldValue.Interface()<br>  }</pre><p>We have used for loop to process all the fields in the provided interface, which we have retrieved with reflectValue.NumField(). Then, we check a condition, i.e., whether the field within the given field is not of struct type. If the condition is true then, we map the key of the field and its corresponding value into result.</p><pre>if fieldValue.Kind() == reflect.Struct {<br>   nestedFields := ToMap(fieldValue.Interface())<br>   for nestedKey, nestedValue := range nestedFields {<br>    result[nestedKey] = nestedValue<br>   }<br>  }<br>}<br> return result<br>}</pre><p>Another condition we check is if the field is struct type. If the condition is true then, we use the recursion property and call the ToMap function within to handle the nested fields. We store the mapped key and its corresponding value in the result.</p><p>This scenario may occur for the cases where a struct is called within another struct. An example of such a case is as follows:</p><pre>type AddressInfo struct{<br> City string `json:&quot;city&quot;`<br> State string `json:&quot;state&quot;`<br> Country string `json:&quot;country&quot;`<br>}<br><br>type GeneralInfo struct {<br> Name    string `json:&quot;name&quot;`<br> Age     int   `json:&quot;age&quot;`<br> AddressInfo<br> Occupation *string `json:&quot;occupation&quot;`<br>}</pre><p>Finally, we return the, which contains the mapped version of the interface.</p><p><strong>Conclusion</strong></p><p>In this article, we have mainly focused on updating nil value. Using reflection instead of mapping each field can be a more efficient and systematic approach. Having said that, the use of reflect is not limited to this and can be used for another purpose as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=212cec203822" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/updating-nil-value-with-gorm-mapping-using-reflect-212cec203822">Updating nil value with GORM (Mapping using Reflect)</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send email using SMTP in Go with and without Transport Layer Security]]></title>
            <link>https://articles.readytowork.jp/send-email-using-smtp-in-go-with-and-without-transport-layer-security-1923f6375c65?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/1923f6375c65</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[smtp]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 17:56:58 GMT</pubDate>
            <atom:updated>2023-07-24T17:56:58.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7EnzFWWfElDWWpTNgAxAg.png" /></figure><p>Writing email is an integral part of our professional life. It is a standard and professional channel to establish communication between two people or parties. While we may use different domains for email, as a developer, we might face a situation where we might have to integrate it in our system as a major feature.</p><p>In this article, we will be going through a similar scenario. We will implement email using SMTP in Go.</p><p>Before jumping into the coding part, let’s look at the project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YOefAQAbfDPvPxUb_VeQBQ.png" /></figure><p>First, lets have a look at the .env file. Here, we will set up the environment variables for our program.</p><pre>SMTP_HOST=YOUR SMTP_HOST<br>SMTP_PORT=YOUR SMTP_PORT<br>EMAIL_FROM=YOUR EMAIL_FROM<br>EMAIL_PASSWORD=YOUR EMAIL_PASSWORD</pre><p><strong>Moving to the email.go file</strong></p><p>Here we will be looking at two different approaches first using simply SMTP and then, adding Transport Layer Security (TLS).</p><p>First, let&#39;s look at the common section for both cases:</p><pre>type Body struct {<br> To string `json:&quot;email_to&quot;`<br>}</pre><p>Here, we have defined a struct, named Body with a field To, which we will use later on to bind json from context.</p><p>Next, we will create a function named SendEmail</p><pre>func SendEmail(c *gin.Context) {<br> var data Body<br> if err := c.BindJSON(&amp;data); err != nil {<br>  //Handle error<br> }<br><br> if err := godotenv.Load(&quot;.env&quot;); err != nil {<br>  //Handle error<br> }<br> emailFrom := os.Getenv(&quot;EMAIL_FROM&quot;)<br> emailPassword := os.Getenv(&quot;EMAIL_PASSWORD&quot;)<br> emailTo := data.To<br> smtpHost := os.Getenv(&quot;SMTP_HOST&quot;)<br> smtpPort := os.Getenv(&quot;SMTP_PORT&quot;)</pre><p>Inside the SendEmail function, first we will use the struct defined earlier to bind json from context. Then, we will load environment variables from .<strong>env</strong> file and initialize the values to different variables accordingly.</p><pre>// Generate a random Message-ID<br> r := rand.New(rand.NewSource(time.Now().UnixNano()))<br> messageID := strconv.FormatInt(r.Int63(), 10) + &quot;@&quot; + smtpHost<br><br> messageBody := &quot;Thank you for reading this article.&quot;<br><br> message := &quot;From: &quot; + emailFrom + &quot;\n&quot; +<br>  &quot;To: &quot; + emailTo + &quot;\n&quot; +<br>  &quot;Subject: &quot; + &quot;This is a subject&quot; + &quot;\n&quot; +<br>  &quot;MIME-version: 1.0;\n&quot; +<br>  &quot;Content-Type: text/html; charset=\&quot;UTF-8\&quot;;\n&quot; +<br>  &quot;Message-ID: &lt;&quot; + messageID + &quot;&gt;\n\n&quot; +<br>  messageBody</pre><p>Next, we will generate a random message id for our email. This step might be avoidable depending on your email host. Then, we will create an overall message of our email where we will initialize the headers for email,i.e., email host, email recipient, subject of the email, MIME-version, Content-Type, and Message-ID, and finally the message body.</p><p>The Content-Type for the email may vary depending upon the content of the body.</p><pre>// Set up authentication<br> auth := smtp.PlainAuth(&quot;&quot;, emailFrom, emailPassword, smtpHost)</pre><p>The last piece of code we will be writing before jumping into our cases is for setting up authentication. We will be using PlainAuth the function, which returns authentication, of the smtp package. As mentioned in the name of the function, the returned authentication implements a plain authentication mechanism using the provided credentials.</p><p><strong>Case 1: Plain SMTP</strong></p><p>We can send the email by using a function of SMTP.</p><pre>err := smtp.SendMail(smtpHost+&quot;:&quot;+smtpPort, auth, emailFrom, []string{emailTo}, []byte(message))<br> if err != nil {<br>  //Handle error<br> }</pre><p><strong>Case 2: Adding Transport Layer Security Connection</strong></p><pre>// TLS configuration<br> tlsConfig := &amp;tls.Config{<br>  InsecureSkipVerify: false,<br>  ServerName:         smtpHost,<br> }<br><br> conn, err := tls.Dial(&quot;tcp&quot;, smtpHost+&quot;:&quot;+smtpPort, tlsConfig)<br> if err != nil {<br>  //Handle error<br> }<br><br> client, err := smtp.NewClient(conn, smtpHost)<br> if err != nil {<br>  //Handle error<br> }<br><br> // Authenticate<br> if err := client.Auth(auth); err != nil {<br>  //Handle error<br> }<br><br> // Set the sender<br> if err := client.Mail(emailFrom); err != nil {<br>  //Handle error<br> }<br><br>// Set the recipient<br> if err := client.Rcpt(emailTo); err != nil {<br>  return<br> }<br><br> wc, err := client.Data()<br> if err != nil {<br>  //Handle error<br> }<br><br> _, err = wc.Write([]byte(message))<br> if err != nil {<br>  //Handle error<br> }<br> err = wc.Close()<br> if err != nil {<br>  //Handle error<br> }<br><br> c.IndentedJSON(http.StatusOK, gin.H{<br>  &quot;response&quot;: &quot;success&quot;,<br>  &quot;message&quot;:  &quot;email sent&quot;,<br> })</pre><p>Breaking down the code:</p><pre>tlsConfig := &amp;tls.Config{<br>  InsecureSkipVerify: false,<br>  ServerName:         smtpHost,<br> }</pre><p>Firstly, we have created an object tlsConfig to configure TLS connection settings. The setting includes the InsecureSkipVerify field set to false and ServerName the field set to the SMTP host.</p><p>The setting for InsecureSkipVerify can vary depending on the server as it is used to verify the server’s certificate.</p><pre>conn, err := tls.Dial(&quot;tcp&quot;, smtpHost+&quot;:&quot;+smtpPort, tlsConfig)<br> if err != nil {<br>  //Handle error<br> }</pre><p>Then, we established a TLS connection using the Dial function, which returns a connection object initialized as conn</p><pre>client, err := smtp.NewClient(conn, smtpHost)<br> if err != nil {<br>  //Handle error<br> }</pre><p>We have established a new SMTP client by passing the TLS connection and SMTP host.</p><pre>// Authenticate<br> if err := client.Auth(auth); err != nil {<br>  //Handle error<br> }<br><br> // Set the sender<br> if err := client.Mail(emailFrom); err != nil {<br>  //Handle error<br> }<br><br>// Set the recipient<br> if err := client.Rcpt(emailTo); err != nil {<br>  return<br> }</pre><p>In the code above, we have authenticated the client with the SMTP server using the authentication created from PlainAuth the function. Then, we have set the sender and recipient to the client.</p><pre>wc, err := client.Data()<br> if err != nil {<br>  //Handle error<br> }<br><br> _, err = wc.Write([]byte(message))<br> if err != nil {<br>  //Handle error<br> }<br> err = wc.Close()<br> if err != nil {<br>  //Handle error<br> }<br><br> c.IndentedJSON(http.StatusOK, gin.H{<br>  &quot;response&quot;: &quot;success&quot;,<br>  &quot;message&quot;:  &quot;email sent&quot;,<br> })</pre><p>Now, we have used the Data method to obtain a writer and initialized it as wc . We have used the Write method of the writer to write the message for the email and after that close the writer. With these steps, the email is sent to the concerned recipient with Transport Layer Security.</p><p><strong>Moving to the main.go file</strong></p><pre>package main<br><br>import (<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/stha-nikhil/go-email/api&quot;<br>)<br><br>func main() {<br> router := gin.Default()<br> router.POST(&quot;/send-email&quot;, api.SendEmail)<br> router.Run()<br>}</pre><p>Here, we have handled the routing for our program. Firstly, we imported the required packages and then, set up a route using the Gin router to call the SendEmailmethod.</p><p><strong>Conclusion</strong></p><p>Since we have gone through the code for both of the cases, let&#39;s dig deeper into their comparison.</p><p>Case 1 is a simpler approach to sending email using SMTP. In this case, no kind of encryption is set up. Case 2 is a more complex approach with multiple steps but includes TLS encryption and is more secure in nature. Now, moving on to the question that we all might be having:</p><h4><strong>Which of these approaches should we adopt?</strong></h4><p>Well, it depends!</p><p>It all depends on the SMTP server you are using to set up your email service. Some SMTP servers may only support plain TCP, while others may require some kind of TLS configuration. Hence, the choice may vary as per the requirement and the use case of the SMTP server that you are using.</p><p>I appreciate your reading. Hope your email finds its way!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1923f6375c65" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/send-email-using-smtp-in-go-with-and-without-transport-layer-security-1923f6375c65">Send email using SMTP in Go with and without Transport Layer Security</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSV File with Go — Support different writing systems in Excel]]></title>
            <link>https://articles.readytowork.jp/csv-file-with-go-support-different-writing-systems-in-excel-d533c091bcdb?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/d533c091bcdb</guid>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Thu, 11 May 2023 19:11:52 GMT</pubDate>
            <atom:updated>2023-05-11T19:11:52.742Z</atom:updated>
            <content:encoded><![CDATA[<h3>CSV File with Go — Support multiple writing systems in Excel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCZIc4bUGmQ4jOlvqpPhTw.png" /></figure><p>If you are a backend developer and have worked in a multilingual application or system, you might have come across this issue while working with CSV. When creating a CSV from the backend and opening the file in Excel, the cell with words of writing systems other than the Latin alphabet is gibberish or full of symbols instead of the word itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*CwsblgfDqpXhPHTCs-RtWg.png" /><figcaption>Image showing the unexpected data in Excel</figcaption></figure><p><em>In the above image, the data in column ‘B’ depicts the issue.</em></p><p>This can be solved by manipulating the file and the settings in the excel; however, doing this for every file might not be the appropriate solution.</p><p>After going through the similar situation, I ran into a solution which worked for me. And this article aims to deliver the same solution.</p><h4><strong>BOM | Byte Order Mark</strong></h4><blockquote>A BOM is used to indicate how a processor places serialized text into a sequence of bytes.</blockquote><p>Basically, BOM is used to indicate the byte order and encoding of a text file. It signals how the bytes in the file should be interpreted. There are byte-order marks for various encodings. We will be using UTF-8 encoding in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*JtEspmUTjMRqt36-4drI3w.png" /></figure><p>Let’s look at how we can implement this in the Go programming language.</p><p><strong>Case 1</strong>: <strong>CSV file with BOM encoding in Go</strong></p><pre>records := []Word{<br>   {&quot;Nepal&quot;, &quot;नमस्ते&quot;, &quot;Hello&quot;},<br>   {&quot;Japan&quot;, &quot;おはよう&quot;, &quot;Good morning&quot;},<br>   {&quot;China&quot;, &quot;你好&quot;, &quot;Hi&quot;},<br>}<br>file, err := os.Create(&quot;records.csv&quot;)<br>bomUtf8 := []byte{0xEF, 0xBB, 0xBF} // Initializing UTF-8 BOM encoding<br>file.Write(bomUtf8) // Writing UTF-8 BOM encoding to the file<br>defer file.Close()<br>if err != nil {<br>   log.Fatalln(&quot;failed to open file&quot;, err)<br>}<br>w := csv.NewWriter(file)<br>defer w.Flush()<br><br>// Using WriteAll<br>var data [][]string<br>for _, record := range records {<br>   row := []string{record.Country, record.Native, record.English}<br>   data = append(data, row)<br>}<br>w.WriteAll(data)</pre><p>In this case, the UTF-8 BOM encoding is initialized and written to the created file before writing the data in it.</p><p><strong>Case 2</strong>: <strong>CSV with BOM encoding in Gin</strong></p><pre>records := [][]string{<br>   {&quot;country&quot;, &quot;Native&quot;, &quot;English&quot;},<br>   {&quot;Nepal&quot;, &quot;नमस्ते&quot;, &quot;Hello&quot;},<br>   {&quot;Japan&quot;, &quot;おはよう&quot;, &quot;Good morning&quot;},<br>   {&quot;China&quot;, &quot;你好&quot;, &quot;Hi&quot;},<br>}<br><br>csvBuffer := new(bytes.Buffer)<br>bomUtf8 := []byte{0xEF, 0xBB, 0xBF}<br>csvBuffer.Write(bomUtf8)<br>writer := csv.NewWriter(csvBuffer) // Create a new CSV writer with UTF-8 BOM encoding<br>writer.WriteAll(records)<br><br>_, err := c.Writer.Write(csvBuffer.Bytes())<br>if err != nil {<br>   log.Fatalln(&quot;Error in writing with context: &quot;, err.Error())<br>}</pre><p>In this case, the UTF-8 BOM encoding is initialized and passed to the writer before writing the data. Since this case is for the server, the changes can be seen once this response is used in the front end to download CSV.</p><h4>Result</h4><p>If you open the created CSV file in Excel, you will see the result as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*7_dYAIvkEnKaIPXB99_vpQ.png" /><figcaption>Image showing the data in Excel with UTF-8 BOM encoding</figcaption></figure><p>Thank you for taking the time to read this article. I hope it was helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d533c091bcdb" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/csv-file-with-go-support-different-writing-systems-in-excel-d533c091bcdb">CSV File with Go — Support different writing systems in Excel</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling CSV in Go Gin]]></title>
            <link>https://articles.readytowork.jp/handling-csv-in-go-gin-600dc2085652?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/600dc2085652</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[csv]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 04:01:49 GMT</pubDate>
            <atom:updated>2023-04-18T04:01:49.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQuSaAl4AUWBbgTsuQmZRQ.gif" /></figure><p>In this article, we will look into how we can work with CSV in Gin, a web framework built in Go. Go has a library, encoding/csv which allows working with the CSV.</p><h4>Project Structure</h4><pre>CSV (Project folder)<br> -&gt; api (folder)<br>   - create_csv.go<br>   - get_csv.go<br> main.go</pre><h4>Creating CSV</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBIvwZelTlmXkG2Y-goOVg.png" /></figure><p>Firstly, we will be working in the <strong>create_csv.go</strong> file in our <strong>API</strong> folder. In this file, we will be writing a function to create CSV.</p><p>Importing the required libraries:</p><pre>import (<br>   &quot;bytes&quot;<br>   &quot;encoding/csv&quot;<br>   &quot;github.com/gin-gonic/gin&quot;<br>   &quot;log&quot;<br>)</pre><p>Let’s look at the function.</p><pre>func CreateCSV(c *gin.Context) {<br> records := [][]string{<br>  {&quot;name&quot;, &quot;age&quot;, &quot;nationality&quot;},<br>  {&quot;Nick Shrestha&quot;, &quot;22&quot;, &quot;Nepali&quot;},<br>  {&quot;Jon Green&quot;, &quot;25&quot;, &quot;American&quot;},<br> }<br><br> csvBuffer := new(bytes.Buffer)<br> writer := csv.NewWriter(csvBuffer)<br> writer.WriteAll(records)<br><br> _, err := c.Writer.Write(csvBuffer.Bytes())<br> if err != nil {<br>  log.Fatalln(&quot;Error in writing with context: &quot;, err.Error())<br> }<br>}</pre><p>Breaking down the function:</p><pre>records := [][]string{<br>      {&quot;name&quot;, &quot;age&quot;, &quot;nationality&quot;},<br>      {&quot;Nick Shrestha&quot;, &quot;22&quot;, &quot;Nepali&quot;},<br>      {&quot;Jon Green&quot;, &quot;25&quot;, &quot;American&quot;},<br>   }</pre><p>Here in the function, we have created a two-dimensional slice of strings, defined as, where each slice represents the data to be stored in each row of the CSV file.</p><pre>csvBuffer := new(bytes.Buffer)</pre><p>Next, we have created a new bytes.Buffer, which facilitates the reading or writing operations from/to the given data. In this function, it will allow us to write the given slice, records, in the CSV file.</p><pre>writer := csv.NewWriter(csvBuffer)</pre><p>Then, we have created a new writer to write into our CSV file.</p><pre>writer.WriteAll(records)</pre><p>We have used WriteAll to write each slice in the records to the writer and call the flush internally.</p><pre>c.Writer.Write(csvBuffer.Bytes())</pre><p>Finally, we have used the Writer form the context to write the CSV file in bytes.</p><h4>Getting CSV</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bvrSyzKFQnF5Z1yU1YU9A.png" /></figure><p>Next, we will be working in the <strong>get_csv.go</strong> file in our <strong>API</strong> folder.</p><p>In this file, we will be writing a function to get a CSV file.</p><p>Importing the required libraries:</p><pre>import (<br>   &quot;encoding/csv&quot;<br>   &quot;github.com/gin-gonic/gin&quot;<br>   &quot;log&quot;<br>   &quot;mime/multipart&quot;<br>   &quot;net/http&quot;<br>)</pre><p>Remaining code:</p><pre>type FileUpload struct {<br>   CSVFile *multipart.FileHeader `form:&quot;file&quot;`<br>}<br><br>type User struct {<br>   Name    string<br>   Age     string<br>   Address string<br>}<br><br>func GetCSV(c *gin.Context) {<br>   var csvfile FileUpload<br>   if err := c.ShouldBind(&amp;csvfile); err != nil {<br>      log.Fatalln(&quot;Error in JSON binding: &quot;, err)<br><br>   }<br><br>   if csvfile.CSVFile == nil {<br>      log.Fatalln(&quot;File is missing&quot;)<br>   }<br><br>   file, err := csvfile.CSVFile.Open()<br>   if err != nil {<br>      log.Fatalln(&quot;Error in opening file&quot;)<br>   }<br>   defer file.Close()<br><br>   records, err := csv.NewReader(file).ReadAll()<br>   if err != nil {<br>      log.Fatalln(&quot;Error in reading file&quot;)<br>   }<br><br>   var users []User<br>   for _, record := range records {<br>      user := User{<br>         Name:    record[0],<br>         Age:     record[1],<br>         Address: record[2],<br>      }<br>      users = append(users, user)<br>   }<br><br>   c.IndentedJSON(http.StatusOK, users)<br>}</pre><p>Let’s breakdown the code:</p><pre>type FileUpload struct {<br>   File *multipart.FileHeader `form:&quot;file&quot;`<br>}</pre><p>We have created a struct, FileUpload, with a field CSVFile of type multipart.FileHeader.</p><pre>type User struct {<br>   Name    string<br>   Age     string<br>   Address string<br>}</pre><p>We have a struct, named User, which we will use to convert data from CSV into a slice.</p><p>Now, let’s shift our focus to <strong>GetCSV</strong> function:</p><pre>func GetCSV(c *gin.Context) {<br>   var csvfile FileUpload<br>   if err := c.ShouldBind(&amp;csvfile); err != nil {<br>      log.Fatalln(&quot;Error in JSON binding: &quot;, err)<br>   }<br><br>   if csvfile.CSVFile == nil {<br>      log.Fatalln(&quot;File is missing&quot;)<br>   }<br><br>   file, err := csvfile.CSVFile.Open()<br>   if err != nil {<br>      log.Fatalln(&quot;Error in opening file&quot;)<br>   }<br>   defer file.Close()<br><br>   records, err := csv.NewReader(file).ReadAll()<br>   if err != nil {<br>      log.Fatalln(&quot;Error in reading file&quot;)<br>   }<br><br>   var users []User<br>   for _, record := range records {<br>      user := User{<br>         Name:    record[0],<br>         Age:     record[1],<br>         Address: record[2],<br>      }<br>      users = append(users, user)<br>   }<br><br>   c.IndentedJSON(http.StatusOK, users)<br>}</pre><p>Breaking down the function:</p><pre>   var csvfile FileUpload<br>   if err := c.ShouldBind(&amp;csvfile); err != nil {<br>      log.Fatalln(&quot;Error in JSON binding: &quot;, err)<br>   }<br><br>   if csvfile.CSVFile == nil {<br>      log.Fatalln(&quot;File is missing&quot;)<br>   }<br><br>   file, err := csvfile.CSVFile.Open()<br>   if err != nil {<br>      log.Fatalln(&quot;Error in opening file&quot;)<br>   }<br>   defer file.Close()</pre><p>Firstly, we have initialized csvFile of the FileUpload struct type and then, used it to serialize the file from form-data. After binding, we checked if the request contains the file or not before proceeding to open the File from csvFile struct to get the FileHeader’s associated file.</p><pre>records, err := csv.NewReader(file).ReadAll()<br>   if err != nil {<br>      log.Fatalln(&quot;Error in reading file&quot;)<br>   }</pre><p>After getting the file, we used the ReadAll function to read all the records of the file, with each record being a slice of fields.</p><pre>var users []User<br>   for _, record := range records {<br>      user := User{<br>         Name:    record[0],<br>         Age:     record[1],<br>         Address: record[2],<br>      }<br>      users = append(users, user)<br>   }<br>c.IndentedJSON(http.StatusOK, users)</pre><p>We have initialized users of []User type. Then, using the for loop, we have stored records to users which is at the end returned as the response.</p><h4>Main</h4><p>Finally, in the main file, we will be using our main function for routing purposes.</p><p>Importing required libraries</p><pre>import (<br>   &quot;github.com/gin-gonic/gin&quot;<br>   &quot;github.com/stha-nikhil/gin-csv/api&quot;<br>)</pre><p><strong>main()</strong></p><pre>func main() {<br>   router := gin.Default()<br>   router.GET(&quot;/csv-create&quot;, api.CreateCSV)<br>   router.POST(&quot;/csv-fetch&quot;, api.GetCSV)<br>   router.Run()<br>}</pre><h4>Results</h4><p><strong>Run</strong> the program with the following command:</p><pre>$ go run main.go</pre><p>You can test this via Postman or another similar platform. The program will respond in this manner:</p><ul><li><strong>API to create CSV</strong></li></ul><p>Test this by creating a GET request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Utuqsf5xar5gr-r4HO2YvQ.png" /><figcaption>A successful response from API to create CSV</figcaption></figure><ul><li><strong>API to fetch from CSV</strong></li></ul><p>Test this by creating a POST request and sending a CSV file as a value to the key ‘file’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*un5Lz5JtFDpa__V6Gq7cuQ.png" /><figcaption>A successful response from API to fetch CSV</figcaption></figure><p>Hope this article has been helpful, thank you for reading.</p><p>Link to the repository: <a href="https://github.com/stha-nikhil/gin-csv">https://github.com/stha-nikhil/gin-csv</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=600dc2085652" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/handling-csv-in-go-gin-600dc2085652">Handling CSV in Go Gin</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle JSON datatype in MySQL using GORM]]></title>
            <link>https://articles.readytowork.jp/handle-json-datatype-in-mysql-using-gorm-1be6d91fb3ac?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be6d91fb3ac</guid>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 12:06:59 GMT</pubDate>
            <atom:updated>2023-04-02T12:06:59.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-yLQ_O6ddgoyG95mSOK7w.png" /></figure><p>While working on a project, I recently bumped into JSON datatype. The JSON datatype is supported by MySQL and carries advantages such as automatic validation of JSON documents and optimized storage format. In this article, we will be using GORM to work with JSON datatype in MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*oBaequQ5AG_Z5HCjoZbUOw.png" /></figure><p>First, let’s create a table to work with. The DDL for the table we will be using in this article is as below:</p><pre>CREATE TABLE `customers` (<br>  `customer_name` varchar(50) NOT NULL,<br>  `customer_type` varchar(45) NOT NULL,<br>  `customer_info` json NOT NULL,<br>  PRIMARY KEY (`customer_name`)<br>) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4</pre><p>After we have created a table named, customers in our database, we will be working with the table using GORM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1LWtJ6Ab6foQ2Zvr9tF5Q.gif" /></figure><p>We need to import the library for datatypes to work with JSON datatypes.</p><p>Then, we need to create a struct of similar fields to our table.</p><p>Then, we need to create a struct of similar fields to our table.</p><pre>type Customer struct {<br>   CustomerName string<br>   CustomerType string<br>   CustomerInfo datatypes.JSON<br>}</pre><p>In the Customer struct above, we have fields CustomerName and CustomerType of string type and CustomerInfo of JSON type.</p><p>Finally, let’s have a look at various operations that we can perform.</p><p><strong>Inserting into the table</strong>:</p><pre>DB.Create(&amp;Customer{<br>   CustomerName: &quot;Customer-1&quot;,<br>   CustomerType: &quot;Type-1&quot;,<br>   CustomerInfo: []byte(`{&quot;age&quot;: 18, &quot;tags&quot;: [&quot;tag1&quot;, &quot;tag2&quot;], &quot;address&quot;: {&quot;city&quot;: &quot;dharan&quot;, &quot;district&quot;:&quot;sunsari&quot;}}`),<br>})</pre><p><strong>Finding data from the table</strong>:</p><ol><li>To find an entry using the key in the column with JSON data</li></ol><pre><br>var customerDetail Customer<br>DB.Find(&amp;customerDetail, datatypes.JSONQuery(&quot;customer_info&quot;).HasKey(&quot;age&quot;))<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBdkYhS_mVUZ2A2jxBNmKA.png" /><figcaption>Image: Screenshot of customerDetail printed in console</figcaption></figure><p>2. To find an entry with multiple keys in the column with JSON data</p><pre>var customerDetail Customer<br>DB.Find(&amp;customerDetail, datatypes.JSONQuery(&quot;customer_info&quot;).HasKey(&quot;address&quot;, &quot;city&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBdkYhS_mVUZ2A2jxBNmKA.png" /><figcaption>Image: Screenshot of customerDetail printed in console</figcaption></figure><p>3. To check JSON extract value from keys equal to the value</p><pre>//extracting value with a single key<br>DB.Find(&amp;customerDetail, datatypes.JSONQuery(&quot;customer_info&quot;).Equals(18, &quot;age&quot;))<br><br><br>//extracting value with multiple keys<br>DB.Find(&amp;customerDetail, datatypes.JSONQuery(&quot;customer_info&quot;).Equals(&quot;dharan&quot;, &quot;address&quot;, &quot;city&quot;))</pre><p><strong>Set fields of JSON column</strong></p><ol><li>Set a value on existing key</li></ol><pre>DB.Model(&amp;Customer{}).Where(&quot;customer_name = ?&quot;, &quot;Customer-1&quot;).UpdateColumn(&quot;customer_info&quot;, datatypes.JSONSet(&quot;customer_info&quot;).Set(&quot;age&quot;, 20))</pre><p>Since the field ageexists for the entry where customer_name has the value Customer-1, it updates the value of ageto 20.</p><p>2. Set a new key with a value</p><pre>DB.Model(&amp;Customer{}).Where(&quot;customer_name = ?&quot;, &quot;Customer-1&quot;).UpdateColumn(&quot;customer_info&quot;, datatypes.JSONSet(&quot;customer_info&quot;).Set(&quot;gender&quot;, &quot;female&quot;))</pre><p>In this case, the field genderdoes not exist for the entry where customer_name has the value Customer-1, so this statement adds a new field gender as a key and female as its value.</p><p>There is also another scenario where you might want to have pre-defined fields for the keys in a column with JSON datatype. In such cases, we can use struct embedding.</p><p>We will be using a struct similar to the one we have used above but with some changes.</p><pre>type Customer struct {<br>   CustomerName string<br>   CustomerType string<br>   CustomerInfo CustomerInfo<br>}<br><br>type CustomerInfo struct {<br>   Age     int16  <br>   Gender  string <br>   Address string<br>}</pre><p>However, we are not using datatypes.JSON the datatype of CustomerInfo and instead embedding another struct with the same name. Therefore, we have to implement Scanner / Valuer.</p><p>Scanner / Valuer interfaces help GORM to receive/save the customized data type into the database.</p><pre>import (<br> &quot;database/sql/driver&quot;<br> &quot;encoding/json&quot;<br> &quot;errors&quot;<br>)</pre><pre>//Value returns value of CustomerInfo struct and implements driver.Valuer interface<br>func (c CustomerInfo) Value() (driver.Value, error) {<br>   return json.Marshal(c)<br>}<br><br><br>//Scan scans value into Jsonb and implements sql.Scanner interface<br>func (c *CustomerInfo) Scan(value interface{}) error {<br>   b, ok := value.([]byte)<br>   if !ok {<br>      return errors.New(&quot;type assertion to []byte failed&quot;)<br>   }<br>   return json.Unmarshal(b, &amp;c)<br>}</pre><p>After this, we can now smoothly operate our database.</p><p><strong>Inserting into the table</strong>:</p><pre>DB.Create(&amp;Customer{<br>   CustomerName: &quot;Customer-2&quot;,<br>   CustomerType: &quot;Type-1&quot;,<br>   CustomerInfo: CustomerInfo{<br>      Age:     25,<br>      Gender:  &quot;male&quot;,<br>      Address: &quot;province-1&quot;,<br>   },<br>})</pre><p>We can also <strong>find</strong> data, <strong>check values,</strong> and <strong>set fields</strong> of JSON columns by using the same approach as mentioned in the earlier part of this article.</p><p>I appreciate your reading, and I hope this article was helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be6d91fb3ac" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/handle-json-datatype-in-mysql-using-gorm-1be6d91fb3ac">Handle JSON datatype in MySQL using GORM</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One-Time Passcode (OTP) Verification in Go with Twilio Verify]]></title>
            <link>https://articles.readytowork.jp/one-time-passcode-otp-verification-in-go-with-twilio-verify-1ee4f2b26b14?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ee4f2b26b14</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[twilio]]></category>
            <category><![CDATA[otp-verification]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 21:26:37 GMT</pubDate>
            <atom:updated>2023-02-23T21:26:37.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gameYwbfc47q1TiECys2w.gif" /></figure><p>Many of us are already familiar with OTP verification. We have used it on multiple platforms to make our experience more secure. In this article, we will set up OTP verification in the Go programming language with Twilio.</p><p>This article can be divided into two main sections. First, we will focus on the required setup for Twilio, then jump into the coding part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*-r4F8q4aN7DuGnsl0Ym2_g.jpeg" /></figure><p>The setup for Twilio has been further broken down into three different steps. Let’s check each of them.</p><p><strong>Step 1: Twilio Account Setup</strong></p><p>The first thing we need to do is sign-up for Twilio. Twilio provides a limited amount of balance for the trial period. Please follow the link to sign-up: <a href="https://www.twilio.com/try-twilio">https://www.twilio.com/try-twilio</a></p><p>After the registration, you can activate one phone number for your trial period. On the home page, you will see the option to activate the phone number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7rLxrY-RiLH3tQcEwlk6g.png" /></figure><p>Click on the button <strong>Get a Twilio phone number</strong> and follow the further instructions.</p><p>After that, there is a section on the home page on the lower left side for <strong>Account Info</strong>. From there you can get your <strong>Account SID</strong> (1) and <strong>Auth Token </strong>(2), which are important credentials for the OTP verification service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*i2BiW6DyKkwa5zgzuM9rdQ.png" /></figure><p><strong>Step 2: Verification Service in Twilio</strong></p><p>Twilio already has a service for verification. This service not only generates one-time password but also verifies it with the related phone number. There are options for using SMS, voice call, or email for verification. In this article, we will be particularly looking at the SMS option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXPOqbh5Vhf3BhdGbpvs2A.png" /></figure><p>On the home page, click on <strong>Explore Products </strong>and navigate to the <strong>Account security </strong>section and select <strong>Verify</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCuwDTVw4G0lmcz9tubmHw.png" /></figure><p>Click on <strong>Create Service Now </strong>button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_whqfmqgcwS9uxCna68hKQ.png" /></figure><p>On the option to <strong>Create a new Service</strong>, give a <strong>Friendly Name </strong>for the service and click <strong>Create</strong> button. In the image above, the <strong>Friendly Name </strong>has been set as <strong>OTP</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*UQlT280tHug8UjO61NqlnA.png" /></figure><p>Now, the <strong>Verify </strong>service has been set up. The <strong>Service SID </strong>(3) will be later used in our program to access this service. Also, make sure that in the SMS section(4), the channel is enabled since we will be using <strong>SMS </strong>as the verification channel.</p><p><strong>Step 3: Geographic Permissions</strong></p><p>Another important feature of Twilio is <strong>Geographic Permissions</strong>. With this, the user can filter and select the specific locations where the concerned twilio service can be used for the user. Depending on the user selection, a country can or cannot receive voice calls or SMS from the twilio account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkdvfMWHqK_iGsZ3mMHQvw.png" /></figure><p>To enable <strong>Geo permissions </strong>for our service, navigate to <strong>Verify </strong>service through <strong>Explore Products </strong>as we did in <strong>Step 2</strong>.<strong> </strong>Now, select <strong>Geo Permissions</strong> to enable the required permission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0P3T3o-T7jjQiBR8DffNTg.png" /></figure><p>Here, you can navigate to the countries for which you want to enable this service and enable the SMS channel and voice channel as required. Don’t forget to save your settings.</p><p>Finally, the required setup for Twilio is complete. We can now jump into the coding section.</p><p><strong>Project Structure</strong></p><pre>verify-otp (Project folder)<br> -&gt; api (folder)<br>   - controller.go<br>   - service.go<br><br> -&gt; config (folder)<br>   - twilio.go<br><br> -&gt; model (folder)<br>   - models.go<br><br> .env <br><br> main.go</pre><p>Let’s dive into the files and respective codes:</p><p>Here is a look at the <strong>.env</strong> file:</p><pre>TWILIO_ACCOUNT_SID=Add your account Service ID(1) here<br>TWILIO_SERVICE_SID=Add your Service SID(3) from verify service<br>TWILIO_AUTH_TOKEN=Add your authorization token(2) here</pre><p>Inside <strong>model</strong> folder, let’s create a <strong>models.go </strong>file</p><pre>package model<br><br>import &quot;github.com/go-playground/validator/v10&quot;<br><br>type OTPData struct {<br>   PhoneNumber string `json:&quot;phone_number&quot; validate:&quot;required&quot;`<br>}<br><br>type VerifyOTP struct {<br>   VerificationCode string `json:&quot;verification_code&quot; validate:&quot;required&quot;`<br>   OTPData<br>}<br><br><br>func ValidateData(data any) error {<br>  var validate = validator.New()<br>   if err := validate.Struct(data); err != nil {<br>      //handle error<br>   }<br>   return nil<br>}</pre><p>In the <strong>models.go</strong> file, we have created two structures that we will be using in the files to deal with the request to our API.</p><p>OTPData is a struct type that contains PhoneNumber a field and VerifyOTP contains OTPData as well as VerificationCode of string type. We will be implementing this struct in upcoming files.</p><p>Then, we initialized a new validator to validate the field in the structs above.</p><p>ValidateData() the function is declared for the sole purpose of validating data, passed to the function, using the initialized validator.</p><p>Next, inside a folder named <strong>config</strong>, we will create a file, <strong>twilio.go</strong></p><pre>package config<br><br>import (<br>   &quot;github.com/joho/godotenv&quot;<br>   &quot;github.com/twilio/twilio-go&quot;<br>   &quot;os&quot;<br>)<br><br>func TwilioClient() (*twilio.RestClient, string, error) {<br>   if err := godotenv.Load(); err != nil {<br>      return nil, &quot;&quot;, err<br>   }<br>   serviceSID := os.Getenv(&quot;TWILIO_SERVICE_SID&quot;)<br>   authToken := os.Getenv(&quot;TWILIO_AUTH_TOKEN&quot;)<br>   accountSID := os.Getenv(&quot;TWILIO_ACCOUNT_SID&quot;)<br><br>   client := twilio.NewRestClientWithParams(twilio.ClientParams{<br>      Username: accountSID,<br>      Password: authToken,<br>   })<br>   return client, serviceSID, nil<br>}</pre><p>In this file, we have created a function TwilioClient() , which uses the Twilio credentials from <strong>.env</strong> file to create Twilio client and returns the generated client along with the service ID.</p><p>Let’s move on to the <strong>api </strong>folder.</p><p>Here, let’s create a file <strong>service.go</strong></p><pre>package api<br><br>import (<br> &quot;errors&quot;<br> &quot;fmt&quot;<br> twilioApi &quot;github.com/twilio/twilio-go/rest/verify/v2&quot;<br> &quot;verify-otp/config&quot;<br> &quot;verify-otp/model&quot;<br> &quot;strings&quot;<br>)<br><br>func sendOTP(otpData model.OTPData) (string, error) {<br> params := &amp;twilioApi.CreateVerificationParams{}<br> params.SetTo(otpData.PhoneNumber)<br> params.SetChannel(&quot;sms&quot;)<br><br> client, serviceID, err := config.TwilioClient()<br> if err != nil {<br>  return &quot;&quot;, err<br> }<br><br> resp, err := client.VerifyV2.CreateVerification(serviceID, params)<br> if err != nil {<br>  if strings.Contains(err.Error(), &quot;ApiError 60200&quot;) {<br>   err = errors.New(&quot;please enter country code in the phone number&quot;)<br>  }<br>  return &quot;&quot;, err<br> }<br><br> return *resp.Status, nil<br>}<br><br>func VerifyOtp(otpNew model.VerifyOTP) (string, error) {<br> client, serviceID, err := config.TwilioClient()<br> if err != nil {<br>  return &quot;&quot;, err<br> }<br><br> params := &amp;twilioApi.CreateVerificationCheckParams{}<br> params.SetTo(otpNew.PhoneNumber)<br> params.SetCode(otpNew.VerificationCode)<br><br> resp, err := client.VerifyV2.CreateVerificationCheck(serviceID, params)<br> if err != nil {<br>  if strings.Contains(err.Error(), &quot;ApiError 60200&quot;) {<br>   err = errors.New(&quot;please add country code in the phone number&quot;)<br>  }<br>  return &quot;&quot;, err<br> }<br><br> if *resp.Status != &quot;approved&quot; {<br>  err := errors.New(*resp.Status)<br>  return &quot;&quot;, err<br> }<br><br> return *resp.Status, nil<br>}</pre><p>This file deals with the handling of all the operations associated with Twilio. It mainly contains two functions to request and verify the OTP. Let’s take a look at them.</p><p><strong>sendOTP():</strong></p><pre>params := &amp;twilioApi.CreateVerificationParams{}<br>params.SetTo(otpData.PhoneNumber))   <br>params.SetChannel(&quot;sms&quot;)</pre><p>At first, we initialized a variable named params a verification param and set the required value, i.e., the user phone number and the channel to it. Since we will be using SMS service, we have set the channel as sms , however, call be also used as a channel. It determines how the user will be receiving the generated OTP.</p><pre>client, serviceID, err := config.TwilioClient()<br>   if err != nil {<br>      return &quot;&quot;, err<br>   }</pre><p>The function to create twilio client in the config has been called.</p><pre>resp, err := client.VerifyV2.CreateVerification(serviceID, params)<br>   if err != nil {<br>      if strings.Contains(err.Error(), &quot;ApiError 60200&quot;) {<br>         err = errors.New(&quot;please enter country code in the phone number&quot;)<br>      }<br>      return &quot;&quot;, err<br>   }<br>return *resp.Status, nil</pre><p>Now, we use the client to create verification bypassing the setup params and serviceID to the CreateVerification() function. One of the most usual errors that we may receive is if the user has not added a country code to the phone number which is mandatory to create verification.</p><p>Twilio has different error codes labeled for various types of errors. In this case, we check if the error is ApiError 60200 , which means the country code is not included in the phone number while making the request. There are other different error codes that you may use to handle errors in a similar manner.</p><p>Finally, we return the status of the response generated by CreateVerification() function.</p><p><strong>verifyOTP():</strong></p><pre>   client, serviceID, err := config.TwilioClient()<br>   if err != nil {<br>      return &quot;&quot;, err<br>   }<br>   params := &amp;twilioApi.CreateVerificationCheckParams{}<br>   params.SetTo(otpNew.PhoneNumber)<br>   params.SetCode(otpNew.VerificationCode)</pre><p>Here, we have used the TwilioClient() function from <strong>config</strong> to create a client and then, set up the parameters required to check the created password for verification.</p><pre>   resp, err := client.VerifyV2.CreateVerificationCheck(serviceID, params)<br>   if err != nil {<br>      if strings.Contains(err.Error(), &quot;ApiError 60200&quot;) {<br>         err = errors.New(&quot;Please enter country code in the phone number&quot;)<br>      }<br>      return &quot;&quot;, err<br>   }<br><br>   if *resp.Status != &quot;approved&quot; {<br>      err := errors.New(*resp.Status)<br>      return &quot;&quot;, err<br>   }</pre><p>After setting up params , we use the client to check for verification with CreateVerficationCheck() the function. And then, if the response obtained contains approved its status, the verification is successful.</p><p>Next in <strong>api </strong>folder, we will create <strong>controller.go</strong></p><pre>package api<br><br>import (<br>   &quot;github.com/gin-gonic/gin&quot;<br>   &quot;net/http&quot;<br>   &quot;verify-otp/model&quot;<br>)<br><br>func RequestOTP(c *gin.Context) {<br>   var phone model.OTPData<br>   if err := c.BindJSON(&amp;phone); err != nil {<br>      //handle error<br>      return<br>   }<br><br>   if err := model.ValidateData(&amp;phone); err != nil {<br>      //handle error<br>      return<br>   }<br><br>   resp, err := sendOTP(phone)<br>   if err != nil {<br>      //handle error<br>      return<br>   }<br>   c.JSON(http.StatusOK, gin.H{<br>      &quot;result&quot;:   &quot;success&quot;,<br>      &quot;response&quot;: resp,<br>   })<br>}<br><br>func ConfirmOTP(c *gin.Context) {<br>   var data model.VerifyOTP<br>   if err := c.BindJSON(&amp;data); err != nil {<br>      //handle error<br>      return<br>   }<br><br>   if err := model.ValidateData(data); err != nil {<br>      //handle error<br>      return<br>   }<br><br>   resp, err := VerifyOtp(data)<br>   if err != nil {<br>      //handle error<br>      return<br>   }<br>   c.JSON(http.StatusOK, gin.H{<br>      &quot;result&quot;:   &quot;success&quot;,<br>      &quot;response&quot;: resp,<br>   })<br>}</pre><p>The <strong>controller.go</strong> contains two different functions to request the OTP from Twilio and then, verify it. Since we already have the code, let’s break down the happenings of these two functions.</p><pre>func RequestOTP(c *gin.Context) {<br>   var phone model.OTPData<br>   if err := c.BindJSON(&amp;phone); err != nil {<br>      //handle error<br>      return<br>   }<br><br>   if err := model.ValidateData(&amp;phone); err != nil {<br>      //handle error<br>      return<br>   }<br><br>   resp, err := sendOTP(phone)<br>   if err != nil {<br>      //handle error<br>      return<br>   }<br>   c.JSON(http.StatusOK, gin.H{<br>      &quot;result&quot;:   &quot;success&quot;,<br>      &quot;response&quot;: resp,<br>   })<br>}</pre><p><strong>RequestOTP():</strong></p><p>This function handles the initial request made for the OTP. When the user request for the OTP, this function binds the data sent to make a request and validates if all the fields, required to make the requests, are present using the ValidateData() function from the model. Then, it calls the sendOTP() function from the service file and returns the response accordingly.</p><pre>func ConfirmOTP(c *gin.Context) {<br>   var data model.VerifyOTP<br>   if err := c.BindJSON(&amp;data); err != nil {<br>      //handle error<br>      return<br>   }<br><br>   if err := model.ValidateData(data); err != nil {<br>      //handle error<br>      return<br>   }<br><br>   resp, err := VerifyOtp(data)<br>   if err != nil {<br>      //handle error<br>      return<br>   }<br>   c.JSON(http.StatusOK, gin.H{<br>      &quot;result&quot;:   &quot;success&quot;,<br>      &quot;response&quot;: resp,<br>   })<br>}</pre><p><strong>ComfirmOTP():</strong></p><p>This function handles the request to verify the obtained OTP. After the user receives the OTP and sends it back for verification, this function binds the data sent and validates if all the fields, required to make the requests, are present using the ValidateData() function from the model. Then, using the verifyOTP() function from the <strong>service.go</strong> file, it returns the generated response.</p><p>Finally, let’s look at our <strong>main.go </strong>file</p><pre>package main<br><br>import (<br>   &quot;github.com/gin-gonic/gin&quot;<br>   &quot;verify-otp/api&quot;<br>)<br><br>func main() {<br>   router := gin.Default()<br>   router.POST(&quot;/&quot;, api.RequestOTP)<br>   router.POST(&quot;/verify&quot;, api.ConfirmOTP)<br>   router.Run()<br>}</pre><p><strong>main():</strong></p><p>In the <strong>main.go</strong>, we basically have a main() function, where we have initialized and run a router with gin . The router has two different routes setup for RequestOTP() and ConfirmOTP() functions from the controller.</p><h3>Result</h3><p><strong>Run</strong> the program with the following command:</p><pre>$ go run main.go</pre><p>You can test this via Postman or another similar platform by creating a POST request for the given routes.</p><p><strong>Requesting for verification code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*tLCFgViUjvkPKIKsENODrg.png" /><figcaption>Response from request to get OTP</figcaption></figure><p>An SMS will be sent to the phone number added to the request.</p><p><strong>Verifying obtained code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*w73okxZOj_n0loRROGGrOA.png" /><figcaption>Response from verifying received OTP successfully</figcaption></figure><p>Thank you for reading, and I hope this article has been useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ee4f2b26b14" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/one-time-passcode-otp-verification-in-go-with-twilio-verify-1ee4f2b26b14">One-Time Passcode (OTP) Verification in Go with Twilio Verify</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieving Log Entries from Google Cloud Logging in Go]]></title>
            <link>https://articles.readytowork.jp/retrieving-log-entries-from-google-cloud-logging-in-go-68890149ab37?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/68890149ab37</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 20:41:45 GMT</pubDate>
            <atom:updated>2023-01-13T20:41:45.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CvuKrxtgYxY57M05SlYsvA.gif" /></figure><p>Logs are very important for monitoring, troubleshooting, and improving application performance. At present, the Google Cloud Platform has established itself as a major platform with several cloud-based services. Among them, Google Cloud Logging provides storage for logs, and also a user interface, namely the Logs Explorer. While the Logs Explorer provides many functionalities to operate on logs on various levels, working with logs on the programming level can be unavoidable when it may serve as an integral feature of a system.</p><p>In this article, we will focus on retrieving the stored logs in the Google Cloud. We will be exploring two different methods to retrieve the logs; Client Libraries and Google Cloud API.</p><p><strong>Project Structure</strong></p><ol><li>main.go //file containing all the functions that we will be using</li><li>.env //file containing environment variables</li><li>defaultAPiServiceAccountKey.json //service account key generated from the Google Cloud project</li></ol><p><strong>Key Points</strong></p><ol><li>Service key, generated from the google cloud project, is integral to accessing the logs in the cloud.</li><li>Initialize the project id in the .env file to use it in the program.</li><li>Retrieving logs also depends on the retention period. Log entries are stored in Cloud Logging for a limited time.</li></ol><h4>The method I: Using Cloud Logging Client Library</h4><p>Let us <strong>import all libraries </strong>required for performing our operation</p><pre>import (<br>   &quot;cloud.google.com/go/logging&quot;<br>   &quot;cloud.google.com/go/logging/logadmin&quot;<br>   &quot;context&quot;<br>   &quot;fmt&quot;<br>   &quot;github.com/joho/godotenv&quot;<br>   &quot;google.golang.org/api/iterator&quot;<br>   &quot;google.golang.org/api/option&quot;<br>   &quot;log&quot;<br>   &quot;os&quot;<br>   &quot;path/filepath&quot;<br>   &quot;time&quot;<br>)</pre><p>Next, let’s write a function called GetLogEntries() which is responsible to get the log entries from the project based on the cloud.</p><pre>func GetLogEntries(adminClient *logadmin.Client, projectID string) ([]*logging.Entry, error) {<br>   ctx := context.Background()<br>   const name = &quot;stderr&quot;<br>   searchKeyword := &quot;CUSTOM_LOG&quot;<br>   lastMonth := time.Now().AddDate(0, -1, 0).Format(time.RFC3339)<br><br>   var entries []*logging.Entry<br>   iter := adminClient.Entries(ctx, logadmin.Filter(fmt.Sprintf(`logName = &quot;projects/%s/logs/%s&quot; AND textPayload:&quot;%s&quot; AND timestamp &gt; &quot;%s&quot;`, projectID, name, searchKeyword, lastMonth)), logadmin.NewestFirst())<br><br>   for len(entries) &lt; 50 {<br>      entry, err := iter.Next()<br>      if err == iterator.Done {<br>         return entries, nil<br>      }<br>      if err != nil {<br>         return nil, err<br>      }<br>      entries = append(entries, entry)<br>   }<br>   return entries, nil<br>}</pre><p><strong>GetLogEntries()</strong></p><p>This function is taking two arguments adminClient and projectID of *logadmin.Client and string type respectively. To read the log entries from the cloud, Go provides a specific package, <strong>logadmin</strong>, containing a Cloud Logging client which we have used to read logs.</p><p>There may be several logs stored in the cloud storage, which may or may not be of your importance. However, we can use <strong>filters to query the logs</strong> that meet our requirements and the same has been done above. Furthermore, we have used a for loop to iterate through each entry that meets the filtered query and append it to a slice which is finally returned at the end.</p><p>Now, moving to the <strong>main</strong> function</p><pre>func main() {<br>   if err := godotenv.Load(); err != nil {<br>      log.Fatal(&quot;error loading .env file&quot;)<br>   }<br>   ctx := context.Background()<br>   projectID := os.Getenv(&quot;GCLOUD_PROJECT_ID&quot;) <br>   defaultServiceKey, err := filepath.Abs(&quot;./defaultApiServiceAccountKey.json&quot;)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to load defaultApiServiceAccountKey.json file while initializing cloud logging: %v&quot;, err)<br>   }<br><br>   optionWithCredential := option.WithCredentialsFile(defaultServiceKey)<br>   adminClient, err := logadmin.NewClient(ctx, projectID, optionWithCredential)<br>   if err != nil {<br>      log.Fatalf(&quot;Failed to create client: %v&quot;, err)<br>   }<br>   defer adminClient.Close()<br><br>   log.Print(&quot;Fetching and printing log entries&quot;)<br>   entries, err := GetLogEntries(adminClient, projectID)<br>   if err != nil {<br>      log.Fatalf(&quot;error getting entries: %v&quot;, err)<br>   }<br>   for _, entry := range entries {<br>      fmt.Println(entry)<br>   }<br>}</pre><p><strong>main()</strong></p><p>In the main function, we define all the required environments for the operation, such as the project id, and default service key of the concerned project. The main function creates an <strong>admin client</strong> which, along with the project id, is passed to the GetLogEntries(). Finally, the log entries returned from the GetLogEntries() are each printed using <strong>for</strong> loop. Each log entry can be used to retrieve the timestamp, payload, and the name of the log it belongs to, at the very least.</p><p>Finally, the <strong>complete code</strong>:</p><pre>//main.go<br>package main<br><br>import (<br>   &quot;cloud.google.com/go/logging&quot;<br>   &quot;cloud.google.com/go/logging/logadmin&quot;<br>   &quot;context&quot;<br>   &quot;fmt&quot;<br>   &quot;github.com/joho/godotenv&quot;<br>   &quot;google.golang.org/api/iterator&quot;<br>   &quot;google.golang.org/api/option&quot;<br>   &quot;log&quot;<br>   &quot;os&quot;<br>   &quot;path/filepath&quot;<br>   &quot;time&quot;<br>)<br><br>func GetLogEntries(adminClient *logadmin.Client, projectID string) ([]*logging.Entry, error) {<br>   ctx := context.Background()<br>   const name = &quot;stderr&quot;<br>   searchKeyword := &quot;CUSTOM_LOG&quot;<br>   lastMonth := time.Now().AddDate(0, -1, 0).Format(time.RFC3339)<br><br>   var entries []*logging.Entry<br>   iter := adminClient.Entries(ctx, logadmin.Filter(fmt.Sprintf(`logName = &quot;projects/%s/logs/%s&quot; AND textPayload:&quot;%s&quot; AND timestamp &gt; &quot;%s&quot;`, projectID, name, searchKeyword, lastMonth)), logadmin.NewestFirst())<br><br>   for len(entries) &lt; 50 {<br>      entry, err := iter.Next()<br>      if err == iterator.Done {<br>         return entries, nil<br>      }<br>      if err != nil {<br>         return nil, err<br>      }<br>      entries = append(entries, entry)<br>   }<br>   return entries, nil<br>}<br><br><br>func main() {<br>   if err := godotenv.Load(); err != nil {<br>      log.Fatal(&quot;error loading .env file&quot;)<br>   }<br>   ctx := context.Background()<br>   projectID := os.Getenv(&quot;GCLOUD_PROJECT_ID&quot;)<br>   defaultServiceKey, err := filepath.Abs(&quot;./defaultApiServiceAccountKey.json&quot;)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to load defaultApiServiceAccountKey.json file while initializing cloud logging: %v&quot;, err)<br>   }<br><br>   optionWithCredential := option.WithCredentialsFile(defaultServiceKey)<br>   adminClient, err := logadmin.NewClient(ctx, projectID, optionWithCredential)<br>   if err != nil {<br>      log.Fatalf(&quot;Failed to create client: %v&quot;, err)<br>   }<br>   defer adminClient.Close()<br><br>   log.Print(&quot;Fetching and printing log entries&quot;)<br>   entries, err := GetLogEntries(adminClient, projectID)<br>   if err != nil {<br>      log.Fatalf(&quot;error getting entries: %v&quot;, err)<br>   }<br>   for _, entry := range entries {<br>      fmt.Println(entry)<br>   }<br>}</pre><h4>Method II: Using Cloud Logging API</h4><p><strong>Code Implementation</strong></p><p>Let us <strong>import all libraries </strong>required for performing our operation</p><pre>import (<br> &quot;bytes&quot;<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;github.com/joho/godotenv&quot;<br> &quot;golang.org/x/oauth2&quot;<br> oauth2google &quot;golang.org/x/oauth2/google&quot;<br> &quot;io/ioutil&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br> &quot;path/filepath&quot;<br> &quot;time&quot;<br>)</pre><p>Now, we will <strong>declare a struct, </strong>Entry, which we will later use in our function.</p><pre>type Entry struct {<br>   TextPayload string<br>   Timestamp   string<br>}</pre><p>Let’s write a function called ListLogEntries() which is responsible to get the log entries from the project based on the cloud using <strong>Cloud Logging API</strong>.</p><pre>func ListLogEntries(projectID string, token *oauth2.Token) ([]Entry, error) {<br>   name := &quot;stderr&quot;<br>   keyword := &quot;CUSTOM_LOG&quot;<br>   lastMonth := time.Now().AddDate(0, -1, 0).Format(time.RFC3339)<br><br>   filter := fmt.Sprintf(`logName = &quot;projects/%s/logs/%s&quot; AND textPayload:&quot;%s&quot; AND timestamp &gt; &quot;%s&quot;`, projectID, name, keyword, lastMonth)<br><br>   var entries []Entry<br>   nextpageToken := &quot;&quot;<br>   for {<br>      postBody, err := json.Marshal(map[string]interface{}{<br>         &quot;resourceNames&quot;: []string{&quot;projects/&quot; + projectID},<br>         &quot;filter&quot;:        filter,<br>         &quot;orderBy&quot;:       &quot;timestamp desc&quot;,<br>         &quot;pageSize&quot;:      1000,<br>         &quot;pageToken&quot;:     nextpageToken,<br>      })<br>      if err != nil {<br>         err = fmt.Errorf(&quot;unable to marshal json: %v&quot;, err)<br>         return nil, err<br>      }<br><br>      requestBody := bytes.NewBuffer(postBody)<br>      request, err := http.NewRequest(&quot;POST&quot;, &quot;https://logging.googleapis.com/v2/entries:list&quot;, requestBody)<br>      if err != nil {<br>         err = fmt.Errorf(&quot;unable to create request: %v&quot;, err)<br>         return nil, err<br>      }<br><br>      request.Header.Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>      request.Header.Add(&quot;Authorization&quot;, &quot;Bearer &quot;+token.AccessToken)<br><br>      client := &amp;http.Client{}<br>      response, err := client.Do(request)<br>      if err != nil || response.StatusCode != http.StatusOK {<br>         err = fmt.Errorf(&quot;unable to fetch logs: %v&quot;, err)<br>         return nil, err<br>      }<br><br>      body, err := ioutil.ReadAll(response.Body)<br>      if err != nil {<br>         err = fmt.Errorf(&quot;unable to unmarshal response body: %v&quot;, err)<br>         return nil, err<br>      }<br><br>      result := struct {<br>         Entries       []Entry<br>         NextPageToken string<br>      }{}<br>      if err := json.Unmarshal(body, &amp;result); err != nil {<br>         err = fmt.Errorf(&quot;unable to unmarshal response body: %v&quot;, err)<br>         return nil, err<br>      }<br>      entries = append(entries, result.Entries...)<br>      if len(result.Entries) == 0 || result.NextPageToken == &quot;&quot; {<br>         response.Body.Close()<br>         break<br>      } else {<br>         nextpageToken = result.NextPageToken<br>         response.Body.Close()<br>      }<br>   }<br>   return entries, nil<br>}</pre><p><strong>ListLogEntries()</strong></p><p>In the function above, we are sending a <strong>POST request</strong> to get the log entries from Google Cloud. The process has been <strong>iterated with a for loop</strong> so that all the pages returned can be read through the function. The function takes two argument projectID and token of string and *oauth2.Token type respectively to perform the defined operations and return the retrieved entries.</p><p>Since we have our function, let’s break down<strong> the major happenings</strong>:</p><pre>name := &quot;stderr&quot;<br>keyword := &quot;CUSTOM_LOG&quot;<br>lastMonth := time.Now().AddDate(0, -1, 0).Format(time.RFC3339)<br><br>filter := fmt.Sprintf(`logName = &quot;projects/%s/logs/%s&quot; AND textPayload:&quot;%s&quot; AND timestamp &gt; &quot;%s&quot;`, projectID, name, keyword, lastMonth)</pre><p>These are the <strong>filters set up</strong> to find the logs that meet the requirement. It is important to note that the <strong>date in the filter must be in time.RFC3339 format</strong>. There are also other filters available that can be used to make your query more efficient.</p><pre>postBody, err := json.Marshal(map[string]interface{}{<br>   &quot;resourceNames&quot;: []string{&quot;projects/&quot; + projectID},<br>   &quot;filter&quot;:        filter,<br>   &quot;orderBy&quot;:       &quot;timestamp desc&quot;,<br>   &quot;pageSize&quot;:      1000,<br>   &quot;pageToken&quot;:     nextpageToken,<br>})</pre><p>Here, we are <strong>preparing the request body</strong> to send to the API. We have initialized resourceNames, filter, orderBy, pageSize<em> </em>and pageToken<em>. </em>Apart from the resourceNames, other fields are <strong>optional</strong>. The pageSize determines the maximum number of results to return from the request and <strong>must not exceed 1000</strong> or the request will be rejected. The pageToken <strong>retrieves the next batch of results</strong> from the preceding call to this method. For the first request, the nextpageToken is set to empty.</p><pre>requestBody := bytes.NewBuffer(postBody)<br>request, err := http.NewRequest(&quot;POST&quot;, &quot;https://logging.googleapis.com/v2/entries:list&quot;, requestBody)<br>if err != nil {<br>   err = fmt.Errorf(&quot;unable to create request: %v&quot;, err)<br>   return nil, err<br>}<br><br>request.Header.Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>request.Header.Add(&quot;Authorization&quot;, &quot;Bearer &quot;+token.AccessToken)<br><br>client := &amp;http.Client{}<br>response, err := client.Do(request)<br>if err != nil || response.StatusCode != http.StatusOK {<br>   err = fmt.Errorf(&quot;unable to fetch logs: %v&quot;, err)<br>   return nil, err<br>}</pre><p>This part of the code is used to <strong>make a request to the API</strong>.</p><pre>result := struct {<br>   Entries       []Entry<br>   NextPageToken string<br>}{}<br>if err := json.Unmarshal(body, &amp;result); err != nil {<br>   err = fmt.Errorf(&quot;unable to unmarshal response body: %v&quot;, err)<br>   return nil, err<br>}</pre><p>In this section, we have parsed JSON encoded data from the response body and stored it in the struct initialized as result.</p><pre>entries = append(entries, result.Entries...)<br>if len(result.Entries) == 0 || result.NextPageToken == &quot;&quot; {<br>   response.Body.Close()<br>   break<br>} else {<br>   nextpageToken = result.NextPageToken<br>   response.Body.Close()<br>}</pre><p>Finally, we appended the result.Entries to entries of []Entry type just outside the a loop. Then, check whether the length result.Entries is 0 or the result.NextPageToken is empty, if the result matches the condition the loop will break and the function will return the stored entries. On the other hand, if the result.NextPageToken is not empty then the loop inside the function will iterate the same process again.</p><p>Now, moving to the <strong>main</strong> function</p><pre>func main() {<br>   if err := godotenv.Load(); err != nil {<br>      log.Fatal(&quot;error loading .env file&quot;)<br>   }<br>   projectID := os.Getenv(&quot;GCLOUD_PROJECT_ID&quot;)<br><br>   defaultServiceKey, err := filepath.Abs(&quot;./defaultApiServiceAccountKey.json&quot;)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to load defaultApiServiceAccountKey.json file while initializing cloud logging: %v&quot;, err)<br>   }<br><br>   serviceKeyData, err := ioutil.ReadFile(defaultServiceKey)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to read defaultApiServiceAccountKey.json file for getting token: %v&quot;, err)<br>   }<br><br>   //Reading the service key credential to authorize and authenticate request to API<br>   tokenSource, err := oauth2google.JWTAccessTokenSourceWithScope(serviceKeyData, &quot;https://www.googleapis.com/auth/logging.read&quot;)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to create token source from service key data: %v&quot;, err)<br>   }<br><br>   token, err := tokenSource.Token()<br>   if err != nil {<br>      log.Fatalf(&quot;unable to get token from token source: %v&quot;, err)<br>   }<br><br>   entries, err := ListLogEntries(projectID, token)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to list log entries: %v&quot;, err)<br>   }<br><br>   for _, entry := range entries {<br>      fmt.Println(entry)<br>   }<br>}</pre><p><strong>main()</strong></p><p>In the <strong>main function</strong>, we define all the required environments for the project and also retrieve the service key credential to <strong>authorize and authenticate request to the API</strong>. While making a request to the Cloud Logging API, we need to <strong>retrieve token </strong>from the defaultServiceAccountKey.json file. Then, we call the ListLogEntries() function by passing projectID and token and iterate through the log entries returned while printing each of them in the loop.</p><p>Let’s see how the <strong>complete code</strong> looks:</p><pre>package main<br><br>import (<br>   &quot;bytes&quot;<br>   &quot;encoding/json&quot;<br>   &quot;fmt&quot;<br>   &quot;github.com/joho/godotenv&quot;<br>   &quot;golang.org/x/oauth2&quot;<br>   oauth2google &quot;golang.org/x/oauth2/google&quot;<br>   &quot;io/ioutil&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br>   &quot;path/filepath&quot;<br>   &quot;time&quot;<br>)<br><br>type Entry struct {<br>   TextPayload string<br>   Timestamp   string<br>}<br><br>func ListLogEntries(projectID string, token *oauth2.Token) ([]Entry, error) {<br>   name := &quot;stderr&quot;<br>   keyword := &quot;CUSTOM_LOG&quot;<br>   lastMonth := time.Now().AddDate(0, -1, 0).Format(time.RFC3339)<br><br>   filter := fmt.Sprintf(`logName = &quot;projects/%s/logs/%s&quot; AND textPayload:&quot;%s&quot; AND timestamp &gt; &quot;%s&quot;`, projectID, name, keyword, lastMonth)<br><br>   var entries []Entry<br>   nextpageToken := &quot;&quot;<br>   for {<br>      postBody, err := json.Marshal(map[string]interface{}{<br>         &quot;resourceNames&quot;: []string{&quot;projects/&quot; + projectID},<br>         &quot;filter&quot;:        filter,<br>         &quot;orderBy&quot;:       &quot;timestamp desc&quot;,<br>         &quot;pageSize&quot;:      1000,<br>         &quot;pageToken&quot;:     nextpageToken,<br>      })<br>      if err != nil {<br>         err = fmt.Errorf(&quot;unable to marshal json: %v&quot;, err)<br>         return nil, err<br>      }<br><br>      requestBody := bytes.NewBuffer(postBody)<br>      request, err := http.NewRequest(&quot;POST&quot;, &quot;https://logging.googleapis.com/v2/entries:list&quot;, requestBody)<br>      if err != nil {<br>         err = fmt.Errorf(&quot;unable to create request: %v&quot;, err)<br>         return nil, err<br>      }<br><br>      request.Header.Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>      request.Header.Add(&quot;Authorization&quot;, &quot;Bearer &quot;+token.AccessToken)<br><br>      client := &amp;http.Client{}<br>      response, err := client.Do(request)<br>      if err != nil || response.StatusCode != http.StatusOK {<br>         err = fmt.Errorf(&quot;unable to fetch logs: %v&quot;, err)<br>         return nil, err<br>      }<br><br>      body, err := ioutil.ReadAll(response.Body)<br>      if err != nil {<br>         err = fmt.Errorf(&quot;unable to unmarshal response body: %v&quot;, err)<br>         return nil, err<br>      }<br><br>      result := struct {<br>         Entries       []Entry<br>         NextPageToken string<br>      }{}<br>      if err := json.Unmarshal(body, &amp;result); err != nil {<br>         err = fmt.Errorf(&quot;unable to unmarshal response body: %v&quot;, err)<br>         return nil, err<br>      }<br>      entries = append(entries, result.Entries...)<br>      if len(result.Entries) == 0 || result.NextPageToken == &quot;&quot; {<br>         response.Body.Close()<br>         break<br>      } else {<br>         nextpageToken = result.NextPageToken<br>         response.Body.Close()<br>      }<br>   }<br>   return entries, nil<br>}<br><br>func main() {<br>   if err := godotenv.Load(); err != nil {<br>      log.Fatal(&quot;error loading .env file&quot;)<br>   }<br>   projectID := os.Getenv(&quot;GCLOUD_PROJECT_ID&quot;)<br><br>   defaultServiceKey, err := filepath.Abs(&quot;./defaultApiServiceAccountKey.json&quot;)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to load defaultApiServiceAccountKey.json file while initializing cloud logging: %v&quot;, err)<br>   }<br><br>   serviceKeyData, err := ioutil.ReadFile(defaultServiceKey)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to read defaultApiServiceAccountKey.json file for getting token: %v&quot;, err)<br>   }<br><br>   //Reading the service key credential to authorize and authenticate request to API<br>   tokenSource, err := oauth2google.JWTAccessTokenSourceWithScope(serviceKeyData, &quot;https://www.googleapis.com/auth/logging.read&quot;)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to create token source from service key data: %v&quot;, err)<br>   }<br><br>   token, err := tokenSource.Token()<br>   if err != nil {<br>      log.Fatalf(&quot;unable to get token from token source: %v&quot;, err)<br>   }<br><br>   entries, err := ListLogEntries(projectID, token)<br>   if err != nil {<br>      log.Fatalf(&quot;unable to list log entries: %v&quot;, err)<br>   }<br><br>   for _, entry := range entries {<br>      fmt.Println(entry)<br>   }<br>}</pre><h4>Result</h4><p><strong>Run</strong> the program with the following command:</p><pre>$ go run main.go</pre><p>You can check the terminal for the log entries which might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8afqii6ggMwtiQJ5BK2yw.png" /></figure><p>The fields and structure of the log entries will depend on the format in which they have been stored.</p><h4>Conclusion</h4><p>Both method I and method II can be used for the effective retrieval of log entries. If you are looking for the answer to which one is the best among them, the answer might depend upon what you are planning to achieve. For example, if you are trying to retrieve a large number of log entries then, using method I, i.e., Cloud Client Library might not be the best option for you as it iterates through each log to retrieve them which can make the whole process time-consuming and in such scenarios, using Cloud API can be more efficient.</p><p>That’s all for this article. Thank you for reading, and I hope this article has been useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68890149ab37" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/retrieving-log-entries-from-google-cloud-logging-in-go-68890149ab37">Retrieving Log Entries from Google Cloud Logging in Go</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File uploading and handling in Go]]></title>
            <link>https://articles.readytowork.jp/file-uploading-and-handling-in-go-863a6fa8eaec?source=rss-754829880a27------2</link>
            <guid isPermaLink="false">https://medium.com/p/863a6fa8eaec</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[multipart-form-data]]></category>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Nikhil Shrestha]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 13:39:27 GMT</pubDate>
            <atom:updated>2022-12-26T13:39:27.434Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will be focusing on handling file upload in Go programming language. Go has a standard library which makes it easily achievable to upload file. Let’s see how it is done using multipart/form-data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_C7l1BERay7f9tCYwzsz-g.gif" /></figure><p>Let’s write a function named <strong>HandleFile()</strong> which will be handling all the process to upload and handle files.</p><pre>func HandleFile(c *gin.Context) {<br>   err := c.Request.ParseMultipartForm(32 &lt;&lt; 20)<br>   if err != nil {<br>      log.Fatal(err)<br>   }<br><br>   file, handler, err := c.Request.FormFile(&quot;file&quot;)<br>   if err != nil {<br>      //handle error<br>   }<br>   defer file.Close()<br><br>   dstFile, err := os.Create(handler.Filename)<br>   if err != nil {<br>      //handle error<br>   }<br><br>   defer dstFile.Close()<br><br>   _, err = io.Copy(dstFile, file)<br>   if err != nil {<br>     //handle error<br>   }<br><br>   absPath, err := filepath.Abs(dstFile.Name())<br>   if err != nil {<br>      //handle error<br>   }<br><br>   c.JSON(http.StatusOK, gin.H{<br>      &quot;res&quot;:           &quot;success&quot;,<br>      &quot;file location&quot;: absPath,<br>   })<br><br>}</pre><p>Now that we have our function, let’s <strong>breakdown the major happenings</strong>:</p><pre>  err := c.Request.ParseMultipartForm(32 &lt;&lt; 20)</pre><p>ParseMultipartFormparses all the part of the request body. We have allocated 32 Mb in the bytes to the request body to store in memory, and rest if there is, will be stored on disk in temporary files.</p><pre>  file, handler, err := c.Request.FormFile(&quot;file&quot;)</pre><p>FormFileuses the provided form key to return the first file of the key. Not only does it fetches the file, it also fetches the metadata, such as file size and file name, that describes the file.</p><p>The <strong>next part </strong>is associated with <strong>storing the file </strong>received from the request. For this purpose, we will creating a local file</p><pre>dstFile, err := os.Create(handler.Filename)</pre><p>then, copy the file received from the request to the local file.</p><pre>_, err = io.Copy(dstFile, file)</pre><p>Finally, we get the absolute path of the file to check it’s location.</p><pre>absPath, err := filepath.Abs(dstFile.Name())</pre><p>And that’s it! We have done it.</p><p>Here is the complete code:</p><pre>package main<br><br>import (<br>   &quot;github.com/gin-gonic/gin&quot;<br>   &quot;io&quot;<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;os&quot;<br>   &quot;path/filepath&quot;<br>)<br><br><br>func HandleFile(c *gin.Context) {<br>   err := c.Request.ParseMultipartForm(32 &lt;&lt; 20)<br>   if err != nil {<br>      log.Fatal(err)<br>   }<br><br>   file, handler, err := c.Request.FormFile(&quot;file&quot;)<br>   if err != nil {<br>      //handle error<br>   }<br>   defer file.Close()<br><br>   dstFile, err := os.Create(handler.Filename)<br>   if err != nil {<br>      //handle error<br>   }<br><br>   defer dstFile.Close()<br><br>   _, err = io.Copy(dstFile, file)<br>   if err != nil {<br>      //handle error<br>   }<br><br>   absPath, err := filepath.Abs(dstFile.Name())<br>   if err != nil {<br>      //handle error<br>   }<br><br>   c.JSON(http.StatusOK, gin.H{<br>    &quot;response&quot;:      &quot;success&quot;,<br>    &quot;file_path&quot;: absPath,<br>   })<br><br>}<br><br>func main() {<br>   router := gin.Default()<br>   router.POST(&quot;/&quot;, HandleFile)<br>   router.Run()<br>}</pre><p>You can test this via Postman or other similar platform by creating a POST request and sending image in the body as form-data.</p><p>The response will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8jlh2Ap9BGDhgs7zaBrmw.png" /></figure><p>You can also check your file in the absolute path, where you will find your image stored.</p><p>Thank you for reading, and I hope this article has been useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6rWOf51wZG03QnW2EEebDw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=863a6fa8eaec" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/file-uploading-and-handling-in-go-863a6fa8eaec">File uploading and handling in Go</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>