<?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 Prakash Rai on Medium]]></title>
        <description><![CDATA[Stories by Prakash Rai on Medium]]></description>
        <link>https://medium.com/@prakash.rai11599?source=rss-f0300fc92852------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QC_cQ_ZrE31vuwj2pzrYLg@2x.jpeg</url>
            <title>Stories by Prakash Rai on Medium</title>
            <link>https://medium.com/@prakash.rai11599?source=rss-f0300fc92852------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:28:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prakash.rai11599/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrating Stripe Payment with Go(Gin), Gorm, MySQL, and React]]></title>
            <link>https://articles.readytowork.jp/integrating-stripe-payment-with-go-gin-gorm-mysql-and-react-259a52549e65?source=rss-f0300fc92852------2</link>
            <guid isPermaLink="false">https://medium.com/p/259a52549e65</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[stripe]]></category>
            <dc:creator><![CDATA[Prakash Rai]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 16:42:11 GMT</pubDate>
            <atom:updated>2023-04-23T16:42:11.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AX8jPRKhCsTGnKjEhF4EQ.png" /></figure><p>Stripe is a technology company providing payment processing and related services to businesses of all sizes with ease. It is one of the most popular payment platforms, helping small online stores to multinational companies. It is possible to integrate Stripe into their web or mobile apps with only a few lines of code, allowing them to accept payment from their worldwide customers. Stripes provide various payment methods which include credit cards, debit cards, Apple Pay and Google Pay.</p><p>Before starting the article, I am assuming that you have a basic knowledge of Go programming language, Gin framework, Gorm, MySQL, and React Js, and know how to create REST APIs and implement them in React.</p><p>Let’s discuss how we can integrate the stripe payment using Golang and React. The article is divided into three parts for understanding the flow of the integration on the back-end and front-end.</p><h3><strong>1. Create a stripe account</strong></h3><p>Creating an account in Stripe is really easy. You just go to the <a href="https://dashboard.stripe.com/register"><strong>stripe account setup page</strong></a>, follow the steps, fill required fields and you will have your account ready to accept payments.</p><p><a href="https://dashboard.stripe.com/register">Sign Up and Create a Stripe Account | Stripe</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKzQ7vJS1Jmcd0rX9LgocQ.png" /></figure><p>Login to your account after signup and go to the developer&#39;s section by clicking on <strong>Developers</strong>. Inside the Developers page click on the <strong>API keys</strong> tab to get your <strong>publishable</strong> and <strong>secret</strong> keys as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3ekOrC2hn5Z-LuhAfCtbQ.png" /></figure><p>And that’s it you have created your first stripe account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*71wLt40HzZiqlBtSYRsA5A.gif" /></figure><h3><strong>2. Backend Section</strong></h3><p>On the backend side, we will do the following things listed below:</p><ol><li>Create REST API to create products, get all products, and get a single product.</li><li>Create an API that will return the <strong>publishable keys</strong> in response.</li><li>Create an API to create a <strong>payment intent key</strong> using the <strong>secret key</strong> from the stripe to complete the payment transaction.</li></ol><p>This is what that project folder structure looks like for the backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*MXq8bQ7vnFQGTYRmgF9pxw.png" /></figure><p>Now, let’s get started with the coding part;</p><p>First, create your project using:</p><pre>go mod init proj-mido/stripe-gateway</pre><p>Add a <strong>.env</strong> file on the root directory and enter your stripe publishable key and secret key.</p><pre>STRIPE_PUBLISHABLE_KEY=&quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;<br>STRIPE_SECRET_KEY=&quot;xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&quot;</pre><p>Install all the libraries listed below:</p><pre> github.com/gin-contrib/cors <br> github.com/gin-gonic/gin <br> github.com/go-sql-driver/mysql <br> github.com/jinzhu/gorm <br> github.com/joho/godotenv <br> github.com/stripe/stripe-go/v72 </pre><p>Add this inside the <strong>main.go</strong> file.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;proj-mido/stripe-gateway/Config&quot;<br> &quot;proj-mido/stripe-gateway/Models&quot;<br> &quot;proj-mido/stripe-gateway/Routes&quot;<br> &quot;github.com/gin-contrib/cors&quot;<br> &quot;github.com/jinzhu/gorm&quot;<br>)<br><br>var err error<br><br>func main() {<br><br> Config.DB, err = gorm.Open(&quot;mysql&quot;, Config.DbURL(Config.BuildDBConfig()))<br> if err != nil {<br>  fmt.Println(&quot;Status:&quot;, err)<br> }<br> defer Config.DB.Close()<br> Config.DB.AutoMigrate(&amp;Models.Products{})<br> r := Routes.SetupRouter()<br> //running<br> r.Use(cors.Default())<br> r.Run()<br>}</pre><p>Add this to the <strong>Models.go</strong> file for the products.</p><pre>package Models<br><br>type Products struct {<br> Id          uint    `json:&quot;id&quot;`<br> Title       string  `json:&quot;title&quot;`<br> Description string  `json:&quot;description&quot;`<br> Price       float64 `json:&quot;price&quot;`<br>}<br><br>func (b *Products) TableName() string {<br> return &quot;products&quot;<br>}</pre><p>Add this inside the <strong>Database.go</strong> for the database connection:</p><pre>//Config/Database.go package Config<br>package Config<br><br>import (<br> &quot;fmt&quot;<br><br> &quot;github.com/jinzhu/gorm&quot;<br>)<br><br>var DB *gorm.DB<br><br>// DBConfig represents db configuration<br>type DBConfig struct {<br> Host     string<br> Port     int<br> User     string<br> DBName   string<br> Password string<br>}<br><br>func BuildDBConfig() *DBConfig {<br> dbConfig := DBConfig{<br>  Host:     &quot;localhost&quot;,<br>  Port:     3306,<br>  User:     &quot;root&quot;,<br>  Password: &quot;&quot;,<br>  DBName:   &quot;stripe-mido&quot;,<br> }<br> return &amp;dbConfig<br>}<br>func DbURL(dbConfig *DBConfig) string {<br> return fmt.Sprintf(<br>  &quot;%s:%s@tcp(%s:%d)/%s?charset=utf8&amp;parseTime=True&amp;loc=Local&quot;,<br>  dbConfig.User,<br>  dbConfig.Password,<br>  dbConfig.Host,<br>  dbConfig.Port,<br>  dbConfig.DBName,<br> )<br>}</pre><p>Add this inside the P<strong>roducts.go</strong> file which is responsible for all the database interactions like adding, deleting, updating, fetching, etc data.</p><pre>package Repository<br><br>import (<br> &quot;proj-mido/stripe-gateway/Config&quot;<br> &quot;proj-mido/stripe-gateway/Models&quot;<br><br> _ &quot;github.com/go-sql-driver/mysql&quot;<br>)<br><br>func GetAllProducts(products *[]Models.Products) (err error) {<br> if err = Config.DB.Find(products).Error; err != nil {<br>  return err<br> }<br> return nil<br>}<br><br>func CreateProduct(product *Models.Products) (err error) {<br> if err = Config.DB.Create(product).Error; err != nil {<br>  return err<br> }<br> return nil<br>}<br><br>func GetAProduct(product *Models.Products, id string) (Models.Products, error) {<br> err := Config.DB.Where(&quot;id = ?&quot;, id).First(product).Error<br> return *product, err<br>}</pre><p>Add this inside the <strong>Routes.go</strong> file to create routes:</p><pre>package Routes<br><br>import (<br> &quot;proj-mido/stripe-gateway/Controllers&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>//SetupRouter ... Configure routes<br>func SetupRouter() *gin.Engine {<br> r := gin.Default()<br> mido := r.Group(&quot;/mido&quot;)<br> {<br>  mido.GET(&quot;products&quot;, Controllers.GetProducts)<br>  mido.POST(&quot;products&quot;, Controllers.CreateProducts)<br>  mido.GET(&quot;config&quot;, Controllers.Config)<br>  mido.POST(&quot;create-payment-intent&quot;, Controllers.HandleCreatePaymentIntent)<br><br> }<br> return r<br>}</pre><p>Add this inside the<strong> Controllers.go</strong> file:</p><pre>package Controllers<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;os&quot;<br> &quot;proj-mido/stripe-gateway/Models&quot;<br> &quot;proj-mido/stripe-gateway/Repository&quot;<br> &quot;strconv&quot;<br><br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;github.com/joho/godotenv&quot;<br> &quot;github.com/stripe/stripe-go/v72&quot;<br> &quot;github.com/stripe/stripe-go/v72/paymentintent&quot;<br>)<br><br>func GetProducts(c *gin.Context) {<br> var products []Models.Products<br> err := Repository.GetAllProducts(&amp;products)<br> if err != nil {<br>  c.AbortWithStatus(http.StatusNotFound)<br> } else {<br>  c.JSON(http.StatusOK, gin.H{&quot;products&quot;: products})<br> }<br>}<br><br>func CreateProducts(c *gin.Context) {<br> var product Models.Products<br> c.BindJSON(&amp;product)<br> err := Repository.CreateProduct(&amp;product)<br> if err != nil {<br>  c.AbortWithStatus(http.StatusNotFound)<br> } else {<br>  c.JSON(http.StatusOK, product)<br> }<br>}<br><br>func Config(c *gin.Context) {<br><br> err := godotenv.Load()<br> if err != nil {<br>  log.Fatal(&quot;Error loading .env file&quot;)<br> }<br><br> c.JSON(http.StatusOK, gin.H{<br>  &quot;publishableKey&quot;: os.Getenv(&quot;STRIPE_PUBLISHABLE_KEY&quot;),<br> })<br>}<br><br>func HandleCreatePaymentIntent(c *gin.Context) {<br><br> var product Models.Products<br><br> stripe.Key = os.Getenv(&quot;STRIPE_SECRET_KEY&quot;)<br><br> if err := c.ShouldBindJSON(&amp;product); err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>  log.Printf(&quot;ShouldBindJSON: %v&quot;, err)<br>  return<br> }<br><br> product_id := strconv.FormatUint(uint64(product.Id), 10)<br><br> data, err := Repository.GetAProduct(&amp;product, product_id)<br> if err != nil {<br>  c.AbortWithStatus(http.StatusNotFound)<br> }<br><br> // Create a PaymentIntent with amount and currency<br> params := &amp;stripe.PaymentIntentParams{<br>  Amount:   stripe.Int64(int64(data.Price)),<br>  Currency: stripe.String(string(stripe.CurrencyUSD)),<br>  AutomaticPaymentMethods: &amp;stripe.PaymentIntentAutomaticPaymentMethodsParams{<br>   Enabled: stripe.Bool(true),<br>  },<br> }<br><br> pi, err := paymentintent.New(params)<br> log.Printf(&quot;pi.New: %v&quot;, pi.ClientSecret)<br><br> if err != nil {<br>  c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: err.Error()})<br>  log.Printf(&quot;pi.New: %v&quot;, err)<br>  return<br> }<br><br> c.JSON(http.StatusOK, gin.H{<br>  &quot;clientSecret&quot;: pi.ClientSecret,<br> })<br>}</pre><p>Now, let&#39;s mainly discuss the two main functions <strong>Config</strong> and <strong>HandleCreatePaymentIntent </strong>inside the controllers.go file.</p><p><strong>Config: </strong>The config function only returns the publishable key in response which is required in the front.</p><p><strong>HandleCreatePaymentIntent: </strong>The process begins by initializing the Stripe secret key with the aid of an environment variable. Thereafter, it acquires a product ID from the JSON payload of the request and leverages it to obtain the product’s details from the database through the utilization of the <strong>GetAProduct</strong> function found in a Repository package.</p><p>Subsequently, it generates a Payment Intent using the <strong>stripe.PaymentIntentParams</strong> structure by defining the amount, currency, and automated payment method parameters for the transaction. The amount is set to the price of the product in this instance, while the currency is USD. The Payment Intent has automated payment methods enabled through the use of <strong>stripe.PaymentIntentAutomaticPaymentMethodsParams</strong>.</p><p>After the creation of the Payment Intent, the function retrieves its client secret and transmits it back to the client through the response payload in JSON format. The client secret is a unique identifier that provides the client with the ability to validate the payment transaction. If the process encounters any errors, the function sends an error response accompanied by an appropriate error message.</p><p><strong>Testing APIs in Postman</strong></p><p>Let&#39;s test our APIs not and see if they are working as expected or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vsEsFgz4EIscKwW7xcX1Lg.png" /><figcaption>Get products API test</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgDVO2IrWjwYHA_oMEaNNA.png" /><figcaption>Create product API test</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gW0BrgF84RAFVxz40FBR5Q.png" /><figcaption>Get a publishable key API test</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwPJ5UHWUEOKzxN__t03yA.png" /><figcaption>Get client secret for payment transaction API test</figcaption></figure><p>That was all that we needed to do in the backend section for stripe payment. Now, let&#39;s move on to the next and last part of the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ZLronSWbmj4IwGoWepecHQ.gif" /></figure><h3><strong>3. Frontend Section</strong></h3><p>Now that we have completed our backend section integrations. Let’s see what we need to do in ReactJs to accomplish our goal.</p><p>This is the Frontend project file structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*a1SHoLsZD1k_1M0By3PwsQ.png" /></figure><p>Now, to get started create a React app using:</p><pre>npx create-react-app<br>        or<br>yarn create react-app</pre><p>Install the following libraries:</p><pre>yarn add @stripe/react-stripe-js @stripe/stripe-js<br>yarn add react-router-dom</pre><p>Add this code inside<strong> the App.js</strong> file. We will be creating three pages. One for listing products, another for the payment page, and the last one for the payment completion page.</p><pre>import &quot;./App.css&quot;;<br>import { BrowserRouter, Routes, Route } from &quot;react-router-dom&quot;;<br>import Payment from &quot;./Payment&quot;;<br>import Completion from &quot;./Completion&quot;;<br>import Products from &quot;./Products&quot;;<br><br>function App() {<br>  return (<br>    &lt;main&gt;<br>      &lt;BrowserRouter&gt;<br>        &lt;Routes&gt;<br>          &lt;Route path=&quot;/&quot; element={&lt;Products /&gt;} /&gt;<br>          &lt;Route path=&quot;/payment/:productId&quot; element={&lt;Payment /&gt;} /&gt;<br>          &lt;Route path=&quot;/completion&quot; element={&lt;Completion /&gt;} /&gt;<br>        &lt;/Routes&gt;<br>      &lt;/BrowserRouter&gt;<br>    &lt;/main&gt;<br>  );<br>}<br><br>export default App;</pre><p>Inside index.css add this code:</p><pre>@import url(https://medium.com/&quot;https://fonts.googleapis.com/css?family=Raleway&amp;display=swap&quot;);<br><br>:root {<br>  --light-grey: #f6f9fc;<br>  --dark-terminal-color: #0a2540;<br>  --accent-color: #635bff;<br>  --radius: 3px;<br>}<br><br>body {<br>  padding: 20px;<br>  font-family: &quot;Raleway&quot;;<br>  font-size: 1.2em;<br>  color: var(--dark-terminal-color);<br>  display: flex;<br>  justify-content: center;<br>}<br><br>main {<br>  width: 100%;<br>}<br><br>form &gt; * {<br>  margin: 10px 0;<br>}<br><br>button {<br>  background-color: var(--accent-color);<br>}<br><br>button {<br>  background: var(--accent-color);<br>  border-radius: var(--radius);<br>  color: white;<br>  border: 0;<br>  padding: 12px 16px;<br>  margin-top: 16px;<br>  font-weight: 600;<br>  cursor: pointer;<br>  transition: all 0.2s ease;<br>  display: block;<br>}<br>button:hover {<br>  filter: contrast(115%);<br>}<br>button:active {<br>  transform: translateY(0px) scale(0.98);<br>  filter: brightness(0.9);<br>}<br>button:disabled {<br>  opacity: 0.5;<br>  cursor: none;<br>}<br><br>input,<br>select {<br>  display: block;<br>  font-size: 1.1em;<br>  width: 100%;<br>  margin-bottom: 10px;<br>}<br><br>label {<br>  display: block;<br>}<br><br>a {<br>  color: var(--accent-color);<br>  font-weight: 900;<br>}<br><br>small {<br>  font-size: 0.6em;<br>}<br><br>fieldset,<br>input,<br>select {<br>  border: 1px solid #efefef;<br>}<br><br>#payment-form {<br>  border: #f6f9fc solid 1px;<br>  border-radius: var(--radius);<br>  padding: 20px;<br>  margin: 20px 0;<br>  box-shadow: 0 30px 50px -20px rgb(50 50 93 / 25%),<br>    0 30px 60px -30px rgb(0 0 0 / 30%);<br>}<br><br>#messages {<br>  font-family: source-code-pro, Menlo, Monaco, Consolas, &quot;Courier New&quot;;<br>  display: none; /* hide initially, then show once the first message arrives */<br>  background-color: #0a253c;<br>  color: #00d924;<br>  padding: 20px;<br>  margin: 20px 0;<br>  border-radius: var(--radius);<br>  font-size: 0.7em;<br>}</pre><p>Let’s create a product listing page. Add the following code given below:</p><pre>import React, { useEffect, useState } from &quot;react&quot;;<br>import { useNavigate } from &quot;react-router-dom&quot;;<br><br>const Products = () =&gt; {<br>  const [products, setProducts] = useState();<br>  const history = useNavigate();<br><br>  useEffect(() =&gt; {<br>    fetch(&quot;http://localhost:3001/mido/products&quot;).then(async (r) =&gt; {<br>      const { products } = await r.json();<br>      console.log(&quot;first&quot;, products);<br>      setProducts(products);<br>    });<br>  }, []);<br><br>  const handleBuy = (id) =&gt; {<br>    history(`/payment/${id}`);<br>  };<br><br>  return (<br>    &lt;div<br>      style={{<br>        display: &quot;flex&quot;,<br>        flexDirection: &quot;column&quot;,<br>        justifyContent: &quot;center&quot;,<br>        alignItems: &quot;center&quot;,<br>      }}<br>    &gt;<br>      &lt;h2&gt;Buy Products Here&lt;/h2&gt;<br>      &lt;div style={{ display: &quot;flex&quot;, marginTop: &quot;20px&quot; }}&gt;<br>        &lt;br /&gt;<br>        {products?.map((product, i) =&gt; {<br>          return (<br>            &lt;div style={{ padding: &quot;50px&quot; }}&gt;<br>              &lt;div style={{ width: &quot;100%&quot; }}&gt;<br>                &lt;h3&gt;{product?.title}&lt;/h3&gt;<br>                &lt;h3&gt;{product?.description}&lt;/h3&gt;<br>                &lt;h3&gt;<br>                  &lt;strong&gt;${product?.price}&lt;/strong&gt;<br>                &lt;/h3&gt;<br>                &lt;br /&gt;<br>              &lt;/div&gt;<br>              &lt;button onClick={() =&gt; handleBuy(product?.id)}&gt;Buy now&lt;/button&gt;<br>            &lt;/div&gt;<br>          );<br>        })}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Products;</pre><p>Add this to your Completion.js file. This is a simple page that will be rendered if the payment is successful.</p><pre>function Completion(props) {<br>  return &lt;h1&gt;Congratulations!! Payment successful&lt;/h1&gt;;<br>}<br><br>export default Completion;</pre><p>Now, let&#39;s create a payment page using Stripe Elements. The <strong>@stripe/react-stripe-js library</strong> offers an Elements component that enables the integration of Stripe payment features into a React app. To create Stripe Elements such as <strong>CardElement</strong> and <strong>PaymentRequestButtonElement</strong>, the Elements component requires a Stripe prop that resolves to a Promise containing a Stripe instance. This Stripe instance is utilized to generate the Stripe Elements, which are then displayed inside the Elements component.</p><p>The Elements component also takes an <strong>options</strong> prop, which is an object that can include options for the payment form, such as <strong>clientSecret</strong> to confirm the payment on the server, and <strong>locale</strong> to provide localized messages and formatting for the payment form.</p><p>Add the following code to the <strong>Payment.js</strong> file.</p><pre>import { useEffect, useState } from &quot;react&quot;;<br>import { Elements } from &quot;@stripe/react-stripe-js&quot;;<br>import { loadStripe } from &quot;@stripe/stripe-js&quot;;<br>import CheckoutForm from &quot;./CheckouForm&quot;;<br>import { useParams } from &quot;react-router-dom&quot;;<br><br>function Payment() {<br>  const [stripePromise, setStripePromise] = useState(null);<br>  const [clientSecret, setClientSecret] = useState(&quot;&quot;);<br>  const { productId } = useParams();<br><br>  useEffect(() =&gt; {<br>    fetch(&quot;http://localhost:3001/mido/config&quot;).then(async (r) =&gt; {<br>      const { publishableKey } = await r.json();<br>      setStripePromise(loadStripe(publishableKey));<br>    });<br>  }, []);<br><br>  useEffect(() =&gt; {<br>    fetch(&quot;http://localhost:3001/mido/create-payment-intent&quot;, {<br>      method: &quot;POST&quot;,<br>      body: JSON.stringify({<br>        id: parseInt(productId),<br>      }),<br>    }).then(async (result) =&gt; {<br>      var { clientSecret } = await result.json();<br>      setClientSecret(clientSecret);<br>    });<br>  }, [productId]);<br><br><br>  return (<br>    &lt;div style={{}}&gt;<br>      &lt;h1&gt;React Stripe and the Payment Element&lt;/h1&gt;<br>      {clientSecret &amp;&amp; stripePromise &amp;&amp; (<br>        &lt;Elements<br>          stripe={stripePromise}<br>          options={{ clientSecret, locale: &quot;ja&quot; }}<br>        &gt;<br>          &lt;CheckoutForm /&gt;<br>        &lt;/Elements&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Payment;</pre><p>Add the following code to the <strong>CheckoutForm.js</strong> file</p><pre>import { PaymentElement } from &quot;@stripe/react-stripe-js&quot;;<br>import { useState } from &quot;react&quot;;<br>import { useStripe, useElements } from &quot;@stripe/react-stripe-js&quot;;<br><br>export default function CheckoutForm() {<br>  const stripe = useStripe();<br>  const elements = useElements();<br><br>  const [message, setMessage] = useState(null);<br>  const [isProcessing, setIsProcessing] = useState(false);<br><br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br><br>    if (!stripe || !elements) {<br>      // Stripe.js has not yet loaded.<br>      // Make sure to disable form submission until Stripe.js has loaded.<br>      return;<br>    }<br><br>    setIsProcessing(true);<br><br>    const { error } = await stripe.confirmPayment({<br>      elements,<br>      confirmParams: {<br>        return_url: `${window.location.origin}/completion`,<br>      },<br>    });<br><br>    if (error.type === &quot;card_error&quot; || error.type === &quot;validation_error&quot;) {<br>      setMessage(error.message);<br>    } else {<br>      setMessage(&quot;An unexpected error occured.&quot;);<br>    }<br><br>    setIsProcessing(false);<br>  };<br><br>  return (<br>    &lt;form id=&quot;payment-form&quot; onSubmit={handleSubmit}&gt;<br>      &lt;PaymentElement id=&quot;payment-element&quot; /&gt;<br>      &lt;button disabled={isProcessing || !stripe || !elements} id=&quot;submit&quot;&gt;<br>        &lt;span id=&quot;button-text&quot;&gt;<br>          {isProcessing ? &quot;Processing ... &quot; : &quot;Pay now&quot;}<br>        &lt;/span&gt;<br>      &lt;/button&gt;<br>      {/* Show any error or success messages */}<br>      {message &amp;&amp; &lt;div id=&quot;payment-message&quot;&gt;{message}&lt;/div&gt;}<br>    &lt;/form&gt;<br>  );<br>}</pre><p>To render the stripe payment form element we need to use the PaymetElement component provided by the <strong>@stripe/react-stripe-js.</strong></p><p>On submitting the form the <strong>confirmPayment</strong> method takes an object with two properties as an argument: elements and confirmParams. The elements property is an instance of the Elements component from <strong>@stripe/react-stripe-js</strong>. It represents the Stripe Elements that are being used to collect payment information from the user, such as the card number, expiry date, and CVC code.</p><p>The <strong>confirmParams</strong> attribute is a collection that stores the confirmation parameters for the payment intent. At present, the only parameter that is being configured is <strong>return_url</strong>, which determines the web address to which the user will be directed upon successfully finishing the payment process.</p><h3><strong>4. Demo</strong></h3><p>We have finally completed the stripe setup and integration on both the front-end and back-end. Now, let&#39;s run our full-stack project to see if it’s working or not.</p><p>Run the backend server using:</p><pre>go run . <br>  or<br>go run main.go</pre><p>Run the client side using:</p><pre>yarn start<br>    or<br>npm start </pre><p>After running the project you will be able to see the product page rendered with all the products available with their name, description, and price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOtPRfFmYbiVDhn7M9y6qA.png" /></figure><p>You can buy the product by clicking on <strong>Buy now</strong> button. On clicking the button you will be redirected to the payment page where you need to fill in the <strong>card number</strong>, <strong>CVC</strong> <strong>number, expiry date, and country name</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRv9rDyOLL1ZPXuE47rFcA.png" /></figure><p>Currently, we are using a test stripe account, so stripe provides a test card number which is <strong>4242 4242 4242 4242 </strong>and other fields can be filled randomly.</p><p>After the form is filled out. Click on the <strong>Pay now</strong> button to complete your transaction. If the payment is successful, you will be redirected to the completion page as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wn3uRoTTQvOo4pra80rRA.png" /></figure><p>To check if the payment is successful, go to the stripe dashboard and click on the <strong>Payment</strong> tab. Your successful and incomplete payment history can be found there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uAJ1f8o6fk1vlxkRqmzFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Q0-OxzH5-uJ3G6ovPfJELw.gif" /></figure><p>This is a simple implementation of Stripe in React and Go. You can further add more features like saving the payment details in your database, etc. To learn more you can visit their website documentation where everything is explained in detail.</p><p><a href="https://stripe.com/docs/payments">Payments</a></p><p><strong>You can check the GitHub repositories here:</strong></p><ul><li><a href="https://github.com/Prakash171999/stripe-payment-front">GitHub - Prakash171999/stripe-payment-front: Stipe react payment frontend code</a></li><li><a href="https://github.com/Prakash171999/golang-stripe">GitHub - Prakash171999/golang-stripe</a></li></ul><p>Happy coding 🎉 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=259a52549e65" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/integrating-stripe-payment-with-go-gin-gorm-mysql-and-react-259a52549e65">Integrating Stripe Payment with Go(Gin), Gorm, MySQL, and React</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[Understanding Webpack and its fundamentals]]></title>
            <link>https://articles.readytowork.jp/understanding-webpack-and-its-fundamentals-1d6c5d65002c?source=rss-f0300fc92852------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d6c5d65002c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Prakash Rai]]></dc:creator>
            <pubDate>Sun, 12 Mar 2023 18:14:39 GMT</pubDate>
            <atom:updated>2023-03-12T18:14:39.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWT1UQkhrMWd_pLhkxe_5w.png" /></figure><h3>Introduction</h3><p>Webpack is one of the most popular module bundlers used today. I have heard about the word “<strong><em>Webpack</em></strong>” a lot and how it was doing something magical in the web world. So, I had to explore the fundamentals of webpack which I will be sharing today.</p><h4>Webpack</h4><p>If you have used AJAX before which was very popular at the time, developers used to face a common error frequently while using it. Later it was found that the AJAX was to be called first and before the script. There are always dependencies that need to be loaded up and there is a hierarchy that you need to follow.</p><p>Now, Let’s imagine you have hundreds of scripts that need to be loaded up in a particular order. With that, if you also need to load up your custom style sheets, images, fonts, etc. it will probably be a nightmare.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*PFjHEYPyc_ROsAPiXMopCw.gif" /></figure><h4><strong>This is where Webpack comes in to help with your nightmare.</strong></h4><p>Webpack is an open-source module bundler for javascript applications that can take multiple modules or assets and create a single bundle of all the dependencies and code that is to be loaded in the correct order.</p><p>Even when dependencies have complicated inter-relationships or are dispersed over numerous files, this process of bundling and resolving dependencies can help to ensure that the application loads and operates appropriately. Webpack provides various features that can help manage dependencies like lazy loading, code splitting, etc.</p><p>If you are familiar with the React library then you are probably using webpack. React doesn’t come with a default webpack config file. But there are several starter kits and templates available for react that include pre-built webpack config. Some of them include <strong><em>create react app</em></strong>, <strong><em>Next Js</em></strong>, <strong><em>Gatsby</em></strong>, etc. Webpack is not only used for React but can be used in various web development environments both in the front-end and back-end.</p><h3>What are we going to learn?</h3><p>First of all, we will discuss some fundamental features of webpack that we need to understand before going any further to manually config our webpack file. Then create a react app where we will manually config the webpack.</p><h3>Let’s start! Are you ready?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*svBsydbUs7Tf0IzqhnQwqg.gif" /></figure><h3>Important web pack terms:</h3><p><strong>Entry: </strong>The entry point is the starting point for webpack to start bundling your code. It indicates which file should be used to begin building the dependency graph (i.e root file). By default, the entry point value is ./src/index.js but we can customize and specify different or multiple entry points.</p><p>Inside the webpack config file, you can configure it like this:</p><pre>module.exports = {<br>  entry: &quot;./src/index.js&quot;<br>}</pre><p><strong>Output: </strong>The output property indicates webpack where to release the bundle files and what to name them. By default, it is created in the <strong><em>dist</em></strong> folder with the name <strong><em>main.js.</em></strong></p><p>Inside the webpack config file, you can configure it like this:</p><pre>module.exports = {<br>  output: {<br>    path: path.join(__dirname, &quot;/dist&quot;),<br>    filename: &quot;main.js&quot;,<br>    //If you want to create unique bundle file everytime you build the project<br>    //then you can use fullhash like this<br>    // filename:&quot;main.[fullhash].js&quot;]<br>  },<br>}</pre><p><strong>Loaders: </strong>Loaders are the property that helps webpack process different types of files that can be added to the dependency graph as webpack only understands JavaScript and JSON files. There are different loaders to convert source code to the webpack compatible format. <br>For example, a <strong><em>css-loader </em></strong>can turn the CSS into a JavaScript module, when launched, adds the styles to the DOM.</p><p>Mainly, loaders have two properties in webpack configuration:</p><ol><li><strong>test: </strong>It helps identify which file or files should be transformed. Regex is used to achieve that.</li><li><strong>use: </strong>It tells which loader to be used for transforming.</li></ol><p>Inside the webpack config file, you can configure it like this:</p><pre>module.exports = {<br>  module: {<br>    rules: [<br>      {<br>        test: /\.css$/,<br>        use: [<br>          &quot;style-loader&quot;,<br>          &quot;css-loader&quot;,<br>        ], <br>      },<br>  }<br>}<br>//style-loader ----&gt; inject css into DOM.  <br>//css-loader ----&gt; inject css to main.js file.</pre><p><strong>Plugins: </strong>Plugins are JavaScript objects that can execute a wide range of tasks such as modifying the output bundle, and optimizing or minifying the output bundle.</p><p>To use a plugin, we need to <strong><em>require()</em></strong> it and add it to the <strong><em>plugin&#39;s</em></strong> array inside the config file. Plugins can be used multiple times in a configuration for various purposes. We need to create a new instance by calling it with the <strong><em>new</em></strong> operator.</p><p>Inside the webpack config file, you can configure it like this:</p><pre>const HtmlWebpackPlugin = require(&quot;html-webpack-plugin&quot;);<br><br>module.exports = {<br>  //Injecting index.html template to everytime the built is created<br>  plugins: [<br>    new HtmlWebpackPlugin({<br>      template: &quot;./src/index.html&quot;,<br>    }),<br>  ],<br>}</pre><p><strong>Mode: </strong>Mode property helps to set the mode of the bundle to either <strong><em>development</em></strong>, <strong><em>production</em>,</strong> or <strong><em>none</em></strong>. The default value for mode is production.</p><p>Inside the webpack config file, you can configure it like this:</p><pre>module.exports = {<br>  mode: &quot;development&quot;<br>}</pre><p><strong>DevServer: </strong>It is a lightweight web server with features like live reloading, hot module replacement, etc. It helps developers to ease the development by previewing the changes without any manual refreshing.</p><p>Inside the webpack config file, you can configure it like this:</p><pre>module.exports = {<br>   devServer: {<br>    host: &quot;localhost&quot;,<br>    port: 8000,<br>    open: true,//Automatically open the browser window when the project starts.<br>  },<br>}</pre><p><strong>Code splitting: </strong>As we know all the application code is bundled into a single file, which can be a problem when the project gets larger. When the single bundle file is called, everything is loaded which affects the application speed.</p><p>So, to counter the issue we can use code splitting which will split the code into different bundle chunks and will only load when needed.</p><p><strong><em>Learn more on webpack concepts here:</em></strong></p><p><a href="https://webpack.js.org/concepts/">Concepts | webpack</a></p><p><strong><em>Congratulations! You have completed halfway to learning webpack. </em></strong>🎉🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*K-yTgauOefeDsqmxlfgpXA.gif" /></figure><h3>Webpack Configuration</h3><p>Now, that you have a fundamental understanding of webpack. Let’s get into configuring your own webpack.</p><p>First, create a react app using:</p><pre>npx create-react-app my-app<br>            or<br>yarn create react-app my-app</pre><p>Now, you should have a react project built. Let’s install the required packages we need for webpack and babel to build and manage the web application.</p><pre>1. npm install --save-dev webpack webpack-dev-server webpack-cli<br>2. npm install --save-dev @babel/core babel-loader @babel/preset-env @babel/preset-react<br>3. npm install --save @babel/runtime<br>4. npm install —save-dev @babel /plugin-transform-runtime<br>5. npm install html-webpack-plugin<br>6. npm install react-loadable</pre><p><strong>a. The first command will install three development dependencies for webpack which are as follows:</strong></p><pre>npm install --save-dev webpack webpack-dev-server webpack-cli</pre><ol><li><strong>webpack</strong>: A module bundler that will be used to bundle the application into a single file.</li><li><strong>webpack-dev-server</strong>: It provides hot reloading and other useful feature while you develop the application.</li><li><strong>webpack-cli</strong>: It will provide a set of commands that can be used to interact with webpack to help configure and customize webpack as per your requirements.</li></ol><p><strong>b</strong>. <strong>The second command will install four dependencies for babel which are as follows:</strong></p><pre>npm install --save-dev @babel/core babel-loader @babel/preset-env @babel/preset-react</pre><ol><li><strong>@babel/core:</strong> The babel compiler&#39;s core will help transform modern JavaScript code to compatible code for older browsers.</li><li><strong>babel-loader:</strong> It helps to transpile(i.e. Converting high level to another high-level language) application code using babel. When the webpack will find the <strong><em>.js </em></strong>extension file, it will pass the file to the babel-loader which will read the file contents and uses babel to transpile the code to a version that is compatible with different environments. This will allow us to use modern JavaScript syntax (i.e. ES6+) while still supporting the older browsers.</li><li><strong>@babel/preset-env:</strong> It is a babel preset which includes a set of plugins that are used for transforming modern JavaScript syntax into compatible code for older browsers.</li><li><strong>@babel/preset-react:</strong> It is a babel preset that includes a set of plugins needed for transforming JSX syntax used in React applications.</li></ol><p><strong>c</strong>.<strong> The third command will install babel runtime dependency in the node.js project, which is used to provide support for certain language characteristics that are not natively available in older versions of JavaScript</strong>.</p><pre>npm install --save @babel/runtime</pre><p><strong>d. The fourth command will install the babel plugin <em>@babel /plugin-</em></strong><em>transform-runtime</em><strong> as a development dependency in your Node.js project. The above package </strong><em>@babel/runtime </em><strong>is used as a runtime dependency along with this plugin.</strong></p><pre>npm install —save-dev @babel /plugin-transform-runtime</pre><p><strong>e.</strong> The fifth command installs a webpack plugin which automatically adds script tags to the HTML file for the generated bundles.</p><pre>npm install html-webpack-plugin</pre><p><strong>f.</strong> The sixth command adds the react-loadable package, a higher-order component (HOC) for loading React components with dynamic imports. It enables you to divide your code into smaller chunks and load them as needed, thereby improving the performance of your application.</p><pre>npm install react-loadable</pre><p>Now, that we have installed the above packages, let&#39;s create two files <strong><em>webpack.config.js </em></strong>(webpack configuration file) and <strong><em>.babelrc </em></strong>(babel configuration file) in the root folder.</p><p>Inside the <strong><em>.babelrc</em></strong> file add this code where we are defining the presets and plugins to be used by the babel when transpiring code using Babel.</p><pre>{<br>  &quot;presets&quot;: [&quot;@babel/preset-env&quot;, &quot;@babel/preset-react&quot;],<br>  &quot;plugins&quot;: [[&quot;@babel/transform-runtime&quot;]]<br>}</pre><p>This is what the final project structure looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*cFJST4GqZcyrttvlztP68Q.png" /></figure><p>We are going to create two different pages <strong>home</strong> and <strong>counter </strong>with a CSS file <strong>style.css</strong> which are going to be rendered in the <strong>App.js</strong> file as below:</p><pre>import React from &quot;react&quot;;<br>import { Link, Route, Switch } from &quot;react-router-dom&quot;;<br>import logo from &quot;./react.png&quot;;<br>import &quot;./style.css&quot;;<br>import Loadable from &quot;react-loadable&quot;;<br><br>const LoaderComponent = () =&gt; &lt;p&gt;Please wait. Loading....&lt;/p&gt;;<br><br>const Home = Loadable({<br>  loader: () =&gt; import(/*webpackChunkName:&quot;Homepage&quot;*/ &quot;./Home&quot;),<br>  loading: LoaderComponent,<br>});<br><br>const Counter = Loadable({<br>  loader: () =&gt; import(/*webpackChunkName:&quot;Counterpage&quot;*/ &quot;./Counter&quot;),<br>  loading: LoaderComponent,<br>});<br><br>const App = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;header&quot;&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;<br>            &lt;Link to={&quot;/&quot;}&gt;Home&lt;/Link&gt;<br>          &lt;/li&gt;<br>          &lt;li&gt;<br>            &lt;Link to={&quot;/counter&quot;}&gt;Counter&lt;/Link&gt;<br>          &lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;main-wrapper&quot;&gt;<br>        &lt;img src={logo} alt=&quot;data item&quot; /&gt;<br>        &lt;Switch&gt;<br>          &lt;Route exact path=&quot;/&quot; component={Home} /&gt;<br>          &lt;Route path=&quot;/counter&quot; component={Counter} /&gt;<br>        &lt;/Switch&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default App;</pre><pre>import React from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      Welcome, Hello world!!<br>      &lt;br /&gt;<br>      &lt;p&gt;This is homepage.&lt;/p&gt;<br>      &lt;Link to=&quot;/counter&quot;&gt;{&quot;Go to counter page ---&gt;&quot;}&lt;/Link&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Home;</pre><pre>import React, { useState } from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br>import &quot;./style.css&quot;;<br><br>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;counter-wrapper&quot;&gt;<br>        &lt;p&gt;Counter JS&lt;/p&gt;<br>        &lt;span&gt;{count}&lt;/span&gt;<br>        &lt;div className=&quot;button-container&quot;&gt;<br>          &lt;button className=&quot;btn&quot; onClick={() =&gt; setCount(count + 1)}&gt;<br>            +<br>          &lt;/button&gt;<br>          &lt;button<br>            className=&quot;btn&quot;<br>            onClick={() =&gt; count &gt; 0 &amp;&amp; setCount(count - 1)}<br>          &gt;<br>            -<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;Link to=&quot;/&quot;&gt;{&quot;Go to home page ---&gt;&quot;}&lt;/Link&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Counter;</pre><pre>body {<br>  margin: 0px;<br>}<br><br>.main-wrapper {<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: center;<br>  align-items: center;<br>  min-height: 100vh;<br>}<br><br>.main-wrapper p {<br>  font-size: 40px;<br>  color: rgb(27, 36, 162);<br>}<br><br>.main-wrapper img {<br>  width: 200px;<br>  height: auto;<br>}<br><br>.main-wrapper span {<br>  margin: 50px 0 40px 0;<br>  font-size: 35px;<br>}<br><br>.button-container {<br>  display: flex;<br>  flex-direction: row;<br>  gap: 10px;<br>}<br><br>.btn {<br>  min-width: 80px;<br>  min-height: 30px;<br>}<br><br>.btn:hover {<br>  cursor: pointer;<br>}<br><br>.counter-wrapper {<br>  display: flex;<br>  align-items: center;<br>  flex-direction: column;<br>  margin-bottom: 25px;<br>}<br><br>.header {<br>  display: flex;<br>  align-items: center;<br>  padding: 0 20px;<br>  justify-content: flex-end;<br>  background: rgb(0 60 146);<br>}<br><br>.header ul {<br>  list-style-type: none;<br>  display: flex;<br>  flex-direction: row;<br>  gap: 20px;<br>}<br><br>.header li {<br>  font-size: 16px;<br>}<br><br>.header a {<br>  text-decoration: none;<br>  color: aliceblue;<br>}</pre><p>Create an <strong>index.js</strong> file inside the src folder and add the code given below. We will be injecting this file to the dist directory on every build so that we don’t have to manually update the script source.</p><pre>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;React + webpack R&amp;D&lt;/title&gt;<br>  &lt;script defer src=&quot;main.js&quot;&gt;&lt;/script&gt;&lt;/head&gt; //main.js is our build output name defined in the webpack.config.js<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Open your <strong>package.json</strong> file and replace the <strong>start</strong> and <strong>build</strong> script with this:</p><pre>&quot;start&quot;: &quot;webpack serve --mode development --open --hot&quot;,<br>&quot;build&quot;: &quot;webpack --mode development&quot;,</pre><p>Inside <strong>webpack.config.js</strong> add this code:</p><pre>const port = 8000;<br>const path = require(&quot;path&quot;);<br>const HtmlWebpackPlugin = require(&quot;html-webpack-plugin&quot;);<br><br>module.exports = {<br>  entry: &quot;./src/index.js&quot;,<br>  output: {<br>    path: path.join(__dirname, &quot;/dist&quot;), //bundle output directory<br>    filename: &quot;main.js&quot;,<br>    //If you want to create unique bundle file everytime you build the project then you can use fullhash like this<br>    // filename:&quot;main.[fullhash].js&quot;]<br>    chunkFilename: &quot;[name].bundle.[fullhash].js&quot;, //specifies the naming pattern for any additional chunks that are generated during the bundling process.<br>  },<br>  module: {<br>    rules: [<br>      {//webpack loader rule to handle js files<br>        test: /\.(js)$/, //regex to check the file extension<br>        exclude: /node_modules/,  //Any files or directories with the name &quot;node_modules&quot; will be excluded from the webpack build.<br>        use: {<br>          loader: &quot;babel-loader&quot;, <br>        },<br>      },<br>      { //webpack loader rule to handle css files<br>        test: /\.css$/,<br>        use: [<br>          &quot;style-loader&quot;,<br>          &quot;css-loader&quot;,<br>        ], //style-loader ----&gt; inject css into DOM.  css-loader ----&gt; inject css to main.js file.<br>      },<br>      {<br>        //webpack loader rule to handle image files<br>        //this rule will ensure that any image files imported in the project will be processed and copied <br>       //to the specified outputPath directory with a unique name for caching purposes.<br>        test: /\.(png|svg|jpeg|jpg)$/, //regex to check the file extension for images<br>        use: {<br>          loader: &quot;file-loader&quot;,<br>          options: {<br>            name: &quot;[name].[hash].[ext]&quot;,<br>            outputPath: &quot;images&quot;, //images output path<br>          },<br>        },<br>      },<br>    ],<br>  },<br><br>  plugins: [<br>    new HtmlWebpackPlugin({<br>      template: &quot;./src/index.html&quot;, //Injecting index.html template to everytime the built is created<br>    }),<br>  ],<br>  devServer: {<br>    host: &quot;localhost&quot;,<br>    port: port,<br>    open: true,<br>  },<br>};</pre><h4>Building and running the application</h4><p>If you run the command <strong>npm run build </strong>it will build a bundle with <strong>main.js</strong> inside the <strong>dist</strong> folder. And you can use <strong>npm run start</strong> to start the server and which will run the <strong>main.js</strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMoOy_q9UdQ9h_cPGDJbZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*UpTrc-ZdLDNsQLz0jwc92A.png" /></figure><p>In the above images, we can see that the bundle files and images were generated after building the application.</p><p>Now, let&#39;s run the application using <strong>npm run start.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMoOy_q9UdQ9h_cPGDJbZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PO57VkLrpaRhlGFr1vpQ_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWlcRA8jRBMcWCbUBVSq_Q.png" /></figure><p>If we look closely at the above <strong>2nd</strong> and <strong>3rd</strong> images, we can see that the page bundle files are only loaded when required.</p><p>And that’s how you can config your own webpack file according to your needs.</p><p><strong>You can access the source code from here:</strong> <a href="https://github.com/Prakash171999/webpack-rnd/tree/develop/webpack-react-rnd">https://github.com/Prakash171999/webpack-rnd/tree/develop/webpack-react-rnd</a></p><p>Happy coding 🎉 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d6c5d65002c" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/understanding-webpack-and-its-fundamentals-1d6c5d65002c">Understanding Webpack and its fundamentals</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[Optimizingthe react-native application performance]]></title>
            <link>https://articles.readytowork.jp/optimizingthe-react-native-application-performance-9a51771af72d?source=rss-f0300fc92852------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a51771af72d</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-applications]]></category>
            <dc:creator><![CDATA[Prakash Rai]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 17:41:41 GMT</pubDate>
            <atom:updated>2023-01-03T17:41:41.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing react-native application performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARDq1NX3MpjuaccSqse72A.png" /></figure><h3><strong>A short introduction to React-Native</strong></h3><p>React Native is a mobile app development framework that allows developers to build cross-platform apps using JavaScript. It provides a bridge between JavaScript and the native code, enabling the two parts to communicate and work together. While React Native aims to provide everything needed for building a high-performing app, there may be times when manual optimization is required to ensure optimal performance. To achieve this, developers need to have a performance-focused mindset and be proactive about optimizing their apps.</p><p>React Native utilizes Metro, a packaging tool developed by Facebook, instead of webpack. While the configuration details may vary, the underlying principles remain unchanged. Facebook is trying to make React Native better by allowing JavaScript and native code to communicate directly through the JavaScript Interface (JSI). However, in the current system, problems can happen when dealing with complicated processes. That is why fixing any issues and making the app run smoothly before using it is essential.</p><p><strong>Let’s look at some of the best practices for improving the performance of a React Native application.</strong></p><h4>1. Use FlatList or SectionList to render large lists instead of using the map in React Native</h4><p>If you have a long list of items, rendering them using the map function will render all the data at once which slows down the app. However, using the FlatList component with lazy loading can help improve performance.</p><p>It only renders the items currently being displayed on the screen and removes them when they are no longer visible. This helps save memory and makes the app run more quickly.</p><pre>import React from &#39;react&#39;<br>import {FlatList} from &#39;react-native&#39;<br><br>const data = [<br>  {<br>    id: 1,<br>    title: &#39;Hello world&#39;<br>  },<br>  {<br>    id: 2,<br>    title: &#39;Hello world 2&#39;<br>  },<br>  ...<br>]<br><br>const App = () =&gt;{<br>    const renderItem = ({item}) =&gt;(<br>        &lt;View&gt;<br>          &lt;Text&gt;{item.title}&lt;/Text&gt;<br>        &lt;/View&gt;<br>    )<br>    return (<br>        &lt;FlatList<br>          data={data}<br>          renderItem={renderItem}<br>          keyExtractor={item =&gt; item.id}<br>        /&gt;<br>    )<br>}</pre><h4>2. Remove all console statements</h4><p>Console statements can be helpful for debugging JavaScript code during the development process, but they should be removed before the app is released to production. If left in the app, these statements can cause serious performance issues in a React Native application. It is important to remember to remove any console statements before bundling the app for release.</p><h4>3. Enable Proguard</h4><p>Proguard is a tool that can help reduce the size of the APK. To use Proguard, you can modify the following line in the android/app/build.gradle file:</p><pre>def enableProguardInReleaseBuilds = true</pre><p>After enabling Proguard you can now enable <strong>minifyEnabled</strong> and <strong>shrinkResources</strong> in your build release to optimize your code. Edit <strong>android/app/build.gradle</strong> to enable.</p><p>Now, after enabling the <strong>Proguard</strong>, <strong>minifyEnabled</strong> and <strong>shrinkResources</strong> can be enabled in your build release to optimize the code. Go to <strong>android/app/build.gradle</strong> to enable.</p><pre>release {<br> debuggable false<br> shrinkResources true<br> minifyEnabled true<br> useProguard true<br> setProguardFiles([getDefaultProguardFile(&#39;proguard-android.txt&#39;), &#39;proguard-rules.pro&#39;])<br>}</pre><h4>4. Using Smaller third-party libraries</h4><p>There are a ton of third-party libraries available which can help ease your software development. But, here we need to understand which library is more suitable for our application. For example, let’s take <strong>momentJs</strong> and <strong>dayJs</strong> as examples to compare them. The images given below will show the memory allocation and its speed. Using the day.js library in place of moment.js can help reduce the size of the <strong>JSBundle</strong> without sacrificing any functionality. This can be done immediately to improve performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N258lDy36mFr0W1e3DjyzA.png" /><figcaption>MomentJs bundle size</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wgdk90yF7vzd8cUI3Sh5fw.png" /><figcaption>dayJs bundle size</figcaption></figure><h4>5. Use cache to optimize images</h4><p>There are some issues that image component causes in the application like rending many images on a single screen, image flickering, low performance in image loading, and cache loading. The issues can be addressed by using a library called <strong>react-native-image</strong>. This library is compatible with both iOS and Android apps and can improve the speed at which images are rendered through a caching system. It also includes features such as authorization headers and other useful capabilities.</p><p>It could be done like this:<br>import FastImage from ‘react-native-fast-image’</p><pre>const App = () =&gt; (<br> &lt;FastImage<br> style={{ width: 400, height: 400 }}<br> source={{<br> uri: &#39;https://unsplash.it/200/200?image=8&#39;,<br> headers: { Authorization: &#39;auth-token&#39; },<br> priority: FastImage.priority.normal,<br> }}<br> resizeMode={FastImage.resizeMode.contain}<br> /&gt;<br>)</pre><h4>6. Use fast-loading image formats</h4><p>Image size is not the only factor that affects the application performance, image format also plays a great role in it. It is required to use <strong>PNG</strong> format for images in react native. <strong>Webp</strong> is the most performant format among the formats. It can reduce the image size by <strong>25%-34%</strong>. It was developed by Google in 2010. But, it is not supported on all devices. The format is supported by Android 4.2.1 and higher devices and iOS 14.</p><h4>7. Avoid Arrow Functions</h4><p>One way to avoid unnecessary re-renders is to avoid using arrow functions as callbacks when rendering screens. These types of functions can be a common cause of inefficiency in rendering.</p><p>It is because using arrow functions as callbacks can result in the creation of a new instance of the function every time the parent component re-renders. This is because a new reference to the function is created each time. This can cause problems with React Native’s ability to reuse old references, leading to inefficient rendering. To avoid this issue, it is recommended to avoid using arrow functions in this way.</p><p>Avoid this approach:</p><pre>import React from &quot;react&quot;;<br><br>const OptimizationExample = () =&gt; {<br>  const optmizeApp = () =&gt; {};<br><br>  return (<br>    &lt;View&gt;<br>      &lt;TouchableOpacity onPress={() =&gt; optmizeApp()} /&gt;<br>    &lt;/View&gt;<br>  )<br>}</pre><p>Use this approach:</p><pre>import React from &quot;react&quot;;<br><br>const OptimizationExample = () =&gt; {<br>  const optmizeApp = () =&gt; {};<br><br>  return (<br>    &lt;View&gt;<br>      &lt;TouchableOpacity onPress={optmizeApp} /&gt;<br>    &lt;/View&gt;<br>  )<br>}</pre><h4>8. Avoid anonymous functions</h4><p>It is common to use inline anonymous functions in JavaScript, but using them in React components can cause performance issues. For example, if the Button component is re-rendered, a new copy of the onPress callback will be created. This can lead to inefficient rendering and should be avoided when possible. Here is an example:</p><pre>&lt;Button<br>  onPress={() =&gt; setCount(count + 1)}<br>  title=&quot;Click me!&quot;<br>/&gt;</pre><p>Using a named function solves this problem. So, now handlePress only needs to be created once.</p><pre>const handlePress = () =&gt; setCount(count + 1)<br><br>&lt;Button<br>  onPress={handlePress}<br>  title=&quot;Click me!&quot;<br>/&gt;</pre><p>Happy Optimizing your code 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a51771af72d" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/optimizingthe-react-native-application-performance-9a51771af72d">Optimizingthe react-native application performance</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[Golang Validation: Make it easy]]></title>
            <link>https://articles.readytowork.jp/golang-validation-make-it-easy-bf8418dbb192?source=rss-f0300fc92852------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8418dbb192</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[validator]]></category>
            <dc:creator><![CDATA[Prakash Rai]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 18:22:53 GMT</pubDate>
            <atom:updated>2022-09-15T18:22:53.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MPLM9HkS8Of-HgEy9ZvXFQ.jpeg" /></figure><p>I am currently new to the Golang programming language and trying to learn most of it due to its growing popularity. But have you ever been in a situation of writing a massive block of code for validation?</p><p>Here’s the approach most of the new Gophers implement while validating in Golang:</p><pre>package main</pre><pre>type User struct {</pre><pre>Email string</pre><pre>FullName string</pre><pre>}</pre><pre>func (a User) IsValid() (errs url.Values) {</pre><pre>if a.FullName == “” {</pre><pre>errs.Add(“name”, “The name is required!”)</pre><pre>}</pre><pre>if len(a.FullName) &lt; 2 || len(a.Name) &gt; 40 {</pre><pre>errs.Add(“name”, “The name field must be between 2–40 chars!”)</pre><pre>}</pre><pre>if a.Email == “” {</pre><pre>errs.Add(“email”, “The email field is required!”)</pre><pre>}</pre><pre>return errs</pre><pre>}</pre><p>Imagine you have to perform a lot of validation following this approach….The approach will become very lengthy and time-consuming, isn&#39;t it?</p><h3><strong>Limitations</strong>:</h3><ul><li>Extremely non-reusable</li><li>Not Flexible</li><li>Time-consuming to maintain when the codebase gets bigger</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*B9wwJa42YAF7pOfOZMlq9Q.gif" /></figure><p>What if there was a function that could handle all of your validation like this?</p><pre>err := ValidateEverythingHere(dto)</pre><pre>if err != nil{</pre><pre>return nil</pre><pre>}</pre><p>Let me introduce you to the <a href="https://github.com/go-playground/validator"><strong><em>Golang validator v10</em></strong></a>, a package that would do all your validation like a piece of cake. You can find the validator here.</p><pre><a href="https://github.com/go-playground/validator">https://github.com/go-playground/validator</a></pre><p>The Validator package comes with features that will handle most of your validations like:</p><ul><li>Struct Validation</li><li>Nested Struct validation</li><li>Individual field validation</li><li>Custom validation by creating your validator tag</li><li>Map and Nested Map validation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*uQwmCksUzXdFOqcjYpFRkQ.gif" /></figure><h3><strong>Installation</strong></h3><p>Use go get to install the package</p><pre>go get github.com/go-playground/validator/v10</pre><p>Then import the validator package into your code using:</p><pre>import &quot;github.com/go-playground/validator/v10&quot;</pre><p>To use this package feature, you have to create its instance.</p><pre>validate := validator.New()</pre><p>Now, let&#39;s try out some go-validation features:</p><h3><strong>Struct Validation</strong></h3><p>let’s create a struct like this:</p><pre>type User struct {<br>   FirstName string `json:&quot;fname&quot; validate:&quot;alpha&quot;`<br>   LastName  string `json:&quot;lname&quot; validate:&quot;alpha&quot;`<br>   Age       uint8  `validate:&quot;gte=20,lte=65&quot;`<br>   Email     string `json:&quot;e-mail&quot; validate:&quot;required,email&quot;`<br>}</pre><p>We can see that there’s a struct tag called to <strong>validate </strong>and there we have defined its validation rules.</p><p>Let’s see how can we validate the above struct:</p><pre>validate = validator.New()</pre><pre>user := &amp;User{<br>   FirstName: &quot;Test&quot;,<br>   LastName:  &quot;Test&quot;,<br>   Age:       75,<br>   Email:     &quot;Badger.Smith@&quot;,<br>}</pre><pre>err := validate.Struct(user)<br>fmt.Println(err)</pre><pre>}</pre><p><strong>validate.Struct()</strong> method will validate the new struct values. If errors are found it will return errors like those given below:</p><pre>Key: ‘User.Age’ Error:Field validation for ‘Age’ failed on the ‘lte’ tag<br>Key: ‘User.Email’ Error:Field validation for ‘Email’ failed on the ‘email’ tag</pre><p>This is what the complete code looks like:</p><pre>package main</pre><pre>import (<br>   &quot;fmt&quot;<br>   &quot;github.com/go-playground/validator&quot;<br>)</pre><pre>type User struct {<br>   FirstName string `json:&quot;fname&quot; validate:&quot;alpha&quot;`<br>   LastName  string `json:&quot;lname&quot; validate:&quot;alpha&quot;`<br>   Age       uint8  `validate:&quot;gte=20,lte=65&quot;`<br>   Email     string `json:&quot;e-mail&quot; validate:&quot;required,email&quot;`<br>}</pre><pre>// Using a single instance of Validate, it caches struct info<br>var validate *validator.Validate</pre><pre>func main() {<br>   validate = validator.New()</pre><pre>   user := &amp;User{<br>      FirstName: &quot;Test&quot;,<br>      LastName:  &quot;Test&quot;,<br>      Age:       75,<br>      Email:     &quot;Badger.Smith@&quot;,<br>   }</pre><pre>   err := validate.Struct(user)<br>   fmt.Println(err)</pre><pre>}</pre><h3><strong>Nested Struct Validation</strong></h3><p><strong>RegisterStructValidateMapRules() </strong>accepts validation rules as the first argument and struct as the second argument<strong>. </strong>It registers to validate map rules. Let’s create three different structs for Data, Details, and FamilyMembers.</p><pre>type Data struct {<br>   Name    string<br>   Email   string<br>   Details *Details<br>}<br><br>type Details struct {<br>   FamilyMembers *FamilyMembers<br>   Salary        string<br>}<br><br>type FamilyMembers struct {<br>   FatherName string<br>   MotherName string<br>}</pre><p>Now, create validation rules each for Data, Details, and FamilyMembers.</p><pre>data := Data{<br>   Name:  &quot;PrakashRai&quot;,<br>   Email: &quot;asdf@gmail.com&quot;,<br>   Details: &amp;Details{<br>      Salary: &quot;150000&quot;,<br>      FamilyMembers: &amp;FamilyMembers{<br>         FatherName: &quot;laxman&quot;,<br>         MotherName: &quot;&quot;,<br>      },<br>   },<br>}</pre><pre>//Validation rule for Data<br>rules1 := map[string]string{<br>   &quot;Name&quot;:    &quot;min=4,max=6&quot;,<br>   &quot;Email&quot;:   &quot;required,email&quot;,<br>   &quot;Details&quot;: &quot;required&quot;,<br>}</pre><pre>//Validation rule for Details<br>rules2 := map[string]string{<br>   &quot;Salary&quot;:        &quot;number&quot;,<br>   &quot;FamilyMembers&quot;: &quot;required&quot;,<br>}</pre><pre>//Validation rule for FamilyMembers<br>rules3 := map[string]string{<br>   &quot;FatherName&quot;: &quot;required,min=4,max=32&quot;,<br>   &quot;MotherName&quot;: &quot;required,min=4,max=32&quot;,<br>}</pre><p>To validate the nested structs:</p><pre>validate1.RegisterStructValidationMapRules(rules1, Data{})<br>validate1.RegisterStructValidationMapRules(rules2, Details{})<br>validate1.RegisterStructValidationMapRules(rules3, FamilyMembers{})<br><br>err := validate.Struct(data)<br>fmt.Println(err)</pre><p>The output will look like this:</p><pre>Key: &#39;Data.Name&#39; Error:Field validation for &#39;Name&#39; failed on the &#39;max&#39; tag<br>Key: &#39;Data.Details.FamilyMembers.MotherName&#39; Error:Field validation for &#39;MotherName&#39; failed on the &#39;required&#39; tag</pre><h3><strong>StructExcept</strong></h3><p>This method is used to validate the struct with the exception of selected fields.</p><pre>err := validate.StructExcept(user, &quot;FirstName&quot;, &quot;LastName&quot;)<br><br>if err != nil {<br>   fmt.Println(err.Error())<br></pre><p>Here, all User struct is validated except <strong>FirstName</strong> and <strong>LastName</strong>.</p><h3><strong>Individual Field Validation</strong></h3><p>You can validate the single variable using the function <strong>validate.Var()</strong>.</p><pre>password := &quot;1234567890&quot;<br>err = validate.Var(password, &quot;required,gte=10&quot;)<br>fmt.Println(err)</pre><h3><strong>Custom Validation Tag</strong></h3><p>The validator package also provides you with the feature to create your own custom tags for validation. Let’s see one of the examples here.</p><p>Create a struct <strong>MyStruct</strong> with validation tag name <strong>is-awesome</strong></p><pre>type MyStruct struct {<br>   String string `validate:&quot;is-awesome&quot;`<br>}</pre><p>Create a function to provide the custom logic for the <strong>is-awesome </strong>tag.</p><pre>//FieldLevel contains all the information and helper functions to validate a field<br>func validateMyVal(fl validator.FieldLevel) bool {<br>   fmt.Println(&quot;fasdfadsfadf&quot;, fl.Field().String())<br>   return fl.Field().String() == &quot;awesome&quot;<br>}</pre><p>The validation logic checks if the string value matches “<strong>awesome</strong>” or not. If the string value is other than “<strong>awesome</strong>” it shows an error message.</p><pre>func main() {<br>   validate2 = validator.New()<br>  <br>   validate2.RegisterValidation(&quot;is-awesome&quot;, validateMyVal)</pre><pre>   //This will not throw any error<br>   s := MyStruct{<br>      String: &quot;awesome&quot;,<br>   }<br><br>   err := validate2.Struct(s)<br>   if err != nil {<br>      fmt.Println(err)<br>   }</pre><pre>   //This will throw an error<br>   s.String = &quot;not awesome&quot;<br>   err = validate2.Struct(s)<br>   if err != nil {<br>      fmt.Println(err)<br>   }<br>}</pre><p><strong>RegisterValidation()</strong> function registers a validation with the given tag.</p><h3><strong>Map Validation</strong></h3><p><strong>ValidateMap()</strong> function is used to validate the map which takes the map as its first argument and validation rules as the second argument.</p><p>Create a map name user and define rules for it.</p><pre>user := map[string]interface{}{<br>   &quot;name&quot;:  &quot;Prakash Rai&quot;,<br>   &quot;email&quot;: &quot;prakash@gmail.com&quot;,<br>}<br><br>rules := map[string]interface{}{<br>   &quot;name&quot;:  &quot;required,min=8,max=32&quot;,<br>   &quot;email&quot;: &quot;omitempty,required,email&quot;,<br>}</pre><p>Now, to check for the validation:</p><pre>errs := validate3.ValidateMap(user, rules)<br><br>if len(errs) &gt; 0 {<br>   fmt.Println(errs)<br>}</pre><pre>//If there is no error, validateMap() method will return empty map of erros, not nil.<br>//To check if there are any errors or not we need to check the length of the return value</pre><p>If there is no error, <strong>validateMap()</strong> function will return an empty map of errors, not nil. To check if there are any errors or not we need to check the length of the return value.</p><h3><strong>Nested Map Validation</strong></h3><p>Nested Map validating is quite similar to map validating the only difference is the map is nested. You need to create validation rules similar to the structure of the nested map.</p><pre>func validateNestedMap() {<br><br>   //A nested map<br>   data := map[string]interface{}{<br>      &quot;name&quot;:  &quot;Prakash Rai&quot;,<br>      &quot;email&quot;: &quot;abc@gmail.com&quot;,<br>      &quot;details&quot;: map[string]interface{}{<br>         &quot;family_members&quot;: map[string]interface{}{<br>            &quot;father_name&quot;: &quot;Laxman&quot;,<br>            &quot;mother_name&quot;: &quot;Bimala&quot;,<br>         },<br>         &quot;salary&quot;: &quot;1000&quot;,<br>         &quot;phones&quot;: []map[string]interface{}{<br>            {<br>               &quot;number&quot;: &quot;9889876765&quot;,<br>               &quot;remark&quot;: &quot;Readytowork&quot;,<br>            },<br>            {<br>               &quot;number&quot;: &quot;9874534456&quot;,<br>               &quot;remark&quot;: &quot;Prakash Devkota&quot;,<br>            },<br>         },<br>      },<br>   }<br><br>   // Rules must be set as the structure as the data itself. If you want to dive into the<br>   // map, just declare its rules as a map<br>   rules := map[string]interface{}{<br>      &quot;name&quot;:  &quot;min=4,max=32&quot;,<br>      &quot;email&quot;: &quot;required,email&quot;,<br>      &quot;details&quot;: map[string]interface{}{<br>         &quot;family_members&quot;: map[string]interface{}{<br>            &quot;father_name&quot;: &quot;required,min=4,max=32&quot;,<br>            &quot;mother_name&quot;: &quot;required,min=4,max=32&quot;,<br>         },<br>         &quot;salary&quot;: &quot;number&quot;,<br>         &quot;phones&quot;: map[string]interface{}{<br>            &quot;number&quot;: &quot;required,min=10,max=10&quot;,<br>            &quot;remark&quot;: &quot;required,min=10,max=45&quot;,<br>         },<br>      },<br>   }<br><br>   if len(validate3.ValidateMap(data, rules)) == 0 {<br>      fmt.Println(&quot;Your nested map data is valid&quot;)<br>      return<br>   }<br><br>   fmt.Println(&quot;Your nested map data is not valid&quot;)<br><br>}</pre><p>You can check for the errors in nested map validation by checking the length of the error. If the length of the returned value is 0 then the nested map is valid.</p><h3>Error Translations</h3><p>Until now we have seen the error messages as shown below which are hardly readable. We will learn how we can translate these errors more readable.</p><pre>Key: &#39;Data.Name&#39; Error:Field validation for &#39;Name&#39; failed on the &#39;max&#39; tag<br>Key: &#39;Data.Details.FamilyMembers.MotherName&#39; Error:Field validation for &#39;MotherName&#39; failed on the &#39;required&#39; tag</pre><p>We will use these packages for our error translations:</p><pre>&quot;github.com/go-playground/locales/en&quot;</pre><pre>ut &quot;github.com/go-playground/universal-translator&quot;</pre><pre>en_translations &quot;github.com/go-playground/validator/v10/translations/en&quot;</pre><p><strong>Universal translator</strong> is an i18n Translator for Golang using CLDR data + pluralization rules.</p><p>Let’s see how the translation of error is performed with examples. First of all, create instances for validator and universal translator</p><pre>var (<br>   uni       *ut.UniversalTranslator<br>   validate4 *validator.Validate<br>)</pre><p>Create a function to translate all the error messages.</p><pre>func translateAll(trans ut.Translator) {<br><br>   type User struct {<br>      Username string `validate:&quot;required&quot;`<br>      Tagline  string `validate:&quot;required,lt=10&quot;`<br>      Tagline2 string `validate:&quot;required,gt=1&quot;`<br>   }<br><br>   user := User{<br>      Username: &quot;&quot;,<br>      Tagline:  &quot;Thid asfsdfdffsdd&quot;, //Space between letters is also counted<br>      Tagline2: &quot;12&quot;,<br>   }<br><br>   err := validate4.Struct(user)<br>   if err != nil {<br><br>      // translate all error at once<br>      errs := err.(validator.ValidationErrors)<br><br>      // returns a map with key = namespace &amp; value = translated error<br>      fmt.Println(errs.Translate(trans))<br>      return<br>   }<br><br>   fmt.Println(&quot;No errors so far&quot;)<br>}</pre><p><strong>translateAll()</strong> function will translate all the errors and returns a map of errors with key = namespace &amp; value = translated error.</p><p>Create a function that will translate individual errors one at a time.</p><pre>func translateIndividual(trans ut.Translator) {<br><br>   type User struct {<br>      Username string `validate:&quot;required&quot;`<br>   }<br><br>   var user User<br><br>   err := validate4.Struct(user)<br>   if err != nil {<br><br>      errs := err.(validator.ValidationErrors)<br><br>      for _, e := range errs {<br>         // can translate each error one at a time.<br>         fmt.Println(e.Translate(trans))<br>      }<br>   }<br>}</pre><p>Inside the <strong>main.go</strong> function write this code:</p><pre>func main() {<br><br>   en := en.New()<br>   uni = ut.New(en, en)<br><br>   // this is usually know or extracted from http &#39;Accept-Language&#39; header<br>   // also see uni.FindTranslator(...)<br>   trans, _ := uni.GetTranslator(&quot;en&quot;)<br><br>   validate4 = validator.New()<br>   en_translations.RegisterDefaultTranslations(validate4, trans)<br>   translateAll(trans)<br>   translateIndividual(trans)<br>}</pre><p><strong>RegisterDefaultTranslations()</strong> registers a set of default translations for all built-in tags in the validator; you may add your own as desired.</p><p>Output translated error for translateAll() function is given below:</p><pre>map[User.Tagline:Tagline must be less than 10 characters in length User.Username:Username is a required field]</pre><p>Output translated error for translateIndividual() function is given below:</p><pre>Username is a required field</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*qWfwQfMXQKX0X_wEK14ybw.gif" /></figure><blockquote>Yesterday I dared to struggle. Today I dare to win. — — <strong>Bernadette Devlin</strong></blockquote><p>Golang validator has a lot of tags that are not mentioned here in this article. You can visit <a href="https://github.com/go-playground/validator">here</a> for more details. Moreover, it also provides a function to register your own tag and error translation. But unfortunately, I found the error translation to be a little bit complicated. Otherwise, once you are done implementing that will surely speed up the development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*gWmPBxxCa9TlKZ45rkcm4w.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8418dbb192" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/golang-validation-make-it-easy-bf8418dbb192">Golang Validation: Make it easy</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[Push notification with firebase, Go and React]]></title>
            <link>https://articles.readytowork.jp/push-notification-with-firebase-go-and-react-b52910923988?source=rss-f0300fc92852------2</link>
            <guid isPermaLink="false">https://medium.com/p/b52910923988</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Prakash Rai]]></dc:creator>
            <pubDate>Mon, 01 Aug 2022 18:12:37 GMT</pubDate>
            <atom:updated>2022-08-01T18:12:37.907Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrA-qBn3i2MfgcLLso1IcA.jpeg" /></figure><h3>What will we be learning in this article?</h3><p>We will learn how we can integrate Firebase push notification to our react app with golang. The article will explain all the process step by step with brief explanation of whats happening.</p><p>Lets divide the article into two section <strong>Front-end</strong> and <strong>Back-end.</strong></p><h3>Back-end Section</h3><p>We need to create a <a href="https://console.firebase.google.com/">Firebase project</a> before configuring Firebase SDK in GO server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*DySV-081Sr4wU3yYE64bdg.png" /></figure><p>After creating the new project navigate to <strong><em>project settings</em></strong> and click on <strong><em>service accounts tab</em></strong>, and then generate a new service account key by clicking on the <strong><em>Generate new private key</em></strong> button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*FTA_-_1u74AC76yKghTwJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Us90ZGXcoerO3SzQ2EeBrQ.png" /></figure><p>After you download the key, rename it as <strong><em>serviceAccountKey.json</em></strong> and copy it to your project root directory. This is all we need from firebase project console.</p><p><strong>Configure and initialize Firebase SDK</strong><br>To use the firebase admin SDK in our GO server we need to add the following packages</p><p>go get firebase.google.com/go/v4<br>go get firebase.google.com/go</p><p>Now, inside the config directory create a new file firebase.go and add the following.</p><pre>package config<br><br>import (<br>    &quot;context&quot;<br>    &quot;path/filepath&quot;<br><br>    firebase &quot;firebase.google.com/go&quot;<br>    &quot;firebase.google.com/go/messaging&quot;<br>    &quot;google.golang.org/api/option&quot;<br>)<br><br>func SetupFirebase() (*firebase.App, context.Context, *messaging.Client) {<br><br>    ctx := context.Background()<br><br>    serviceAccountKeyFilePath, err := filepath.Abs(&quot;./serviceAccountKey.json&quot;)<br>    if err != nil {<br>        panic(&quot;Unable to load serviceAccountKeys.json file&quot;)<br>    }<br><br>    opt := option.WithCredentialsFile(serviceAccountKeyFilePath)<br><br>    //Firebase admin SDK initialization<br>    app, err := firebase.NewApp(context.Background(), nil, opt)<br>    if err != nil {<br>        panic(&quot;Firebase load error&quot;)<br>    }<br><br>    //Messaging client<br>    client, _ := app.Messaging(ctx)<br><br>    return app, ctx, client<br>}</pre><p>Here, we first use absolute filepath to get the path to the serviceAccountKey.json from our current file. Then we create a clientOption with <strong><em>option.WithCredentialsFile()</em></strong> method. We pass this credential clientOption to <strong><em>firebase.NewApp()</em></strong> along with other params, which creates the firebase <strong><em>app</em></strong>. With the firebase app, we can then extract the messaging client with <strong><em>app.Messaging() </em></strong>method.</p><p>For more information on how to initialize firebase admin SDK visit:</p><p><a href="https://firebase.google.com/docs/admin/setup">Add the Firebase Admin SDK to your server</a></p><p>Navigate to your <strong><em>main.go</em></strong> file and paste the following;</p><pre>package main<br><br>import (<br>	&quot;context&quot;<br>	&quot;fmt&quot;<br>	&quot;log&quot;<br><br>	firebase &quot;firebase.google.com/go&quot;<br>	&quot;firebase.google.com/go/messaging&quot;<br>	&quot;github.com/readytowork-org/backend-RnD/config&quot;<br>)<br><br>func main() {<br><br>	app, _, _ := config.SetupFirebase()<br>	sendToToken(app)<br>	}<br><br>func sendToToken(app *firebase.App) {<br>	ctx := context.Background()<br>	client, err := app.Messaging(ctx)<br>	if err != nil {<br>		log.Fatalf(&quot;error getting Messaging client: %v\n&quot;, err)<br>	}<br><br>	registrationToken := &quot;d3adVu0tMDyBUTPkgc_l-0:APA91bHjb6-wWkT1ABGSasFqxrsOR3AdfcTjLc8b7f7yukWLt32GS4UA5XdIwZ8p98oOLp-CBcyuYaCYdEPRji_f2WSXO9JKb7XPjotm_3bdkk-7hJyxJS8JuUHt82xzGGJ6Aacy0QWb&quot;<br><br>	message := &amp;messaging.Message{<br>		Notification: &amp;messaging.Notification{<br>			Title: &quot;Notification Test&quot;,<br>			Body:  &quot;Hello React!!&quot;,<br>		},<br>		Token: registrationToken,<br>	}<br><br>	response, err := client.Send(ctx, message)<br>	if err != nil {<br>		log.Fatalln(err)<br>	}<br>	fmt.Println(&quot;Successfully sent message:&quot;, response)<br>}</pre><p>We can get the <strong><em>app</em></strong> from the <strong><em>SetupFirebase()</em></strong> method which will be imported from <strong><em>config</em></strong> package. Now, create a function <strong><em>sendToToken()</em></strong>. This function sends the push notification to the specific device which it identifies from <strong><em>registration token</em></strong>. We get the messaging <strong><em>client</em></strong> from <strong><em>app.Messaging(ctx).</em></strong><br>Your can get the registration token from the client app which we will discuss in Front-end section.</p><p>Now, when we call the <strong>sendToToken()</strong> function and run the server using <strong><em>go run main.go </em></strong>command, the notification is sent to the device of given registration token and then we get the success message if everything goes right as below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*W-LOE6MD473pSS22oS1AjA.png" /></figure><p>To learn more about building send requests for Firebase messaging visit:</p><p><a href="https://firebase.google.com/docs/cloud-messaging/send-message">Build app server send requests | Firebase Cloud Messaging</a></p><p><em>Congratulations!! that’s all we need to do in the back-end part. Now let’s discuss about the things we need to do in the front-end part.</em></p><h3>Front-end Section</h3><p>We will be using React JS library for our client side. <br>In summary, we will go through the following steps:<br>a. Register the web app in Firebase<br>b. Setup Firebase Configurations in React<br>c. Test the Notification<br>d. Solving the problem of notification not appearing(<strong><em>Optional</em></strong>)</p><p>Login into the <a href="https://console.firebase.google.com/">Firebase console</a> and click on <strong>Add project</strong>. Follow the steps to add the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1neFqtN7c_4gp9zWSoE5Q.png" /></figure><p>After registering the app, we will get the Firebase SDK file as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*zpy6BLCF-vMzqcwjL1JWWA.png" /></figure><p>We will be requiring this configuration in our next step.</p><p><strong>Setup Firebase SDK in React.</strong><br>Install the Firebase dependency in the project using</p><p>npm install firebase</p><p>We will configure Firebase in our project, create a file called firebaseInit.js (<em>We can name it anything</em>)<br>Add the following code to the file:</p><pre>import firebase from &#39;firebase/app&#39;;<br>import &#39;firebase/messaging&#39;;<br>// For Firebase JS SDK v7.20.0 and later, measurementId is optional<br>const firebaseConfig = {<br>  apiKey: &quot;YOUR_API_KEY&quot;,<br>  authDomain: &quot;YOUR_AUTH_DOMAIN&quot;,<br>  projectId: &quot;YOUR_PROJECT_ID&quot;,<br>  storageBucket: &quot;YOUR_STORAGE_BUCKET&quot;,<br>  messagingSenderId: &quot;YOUR_MESSAGING_SENDER_ID&quot;,<br>  appId: &quot;YOUR_APP_ID&quot;,<br>  measurementId: &quot;YOUR MEASUREMENT ID&quot;<br>};<br>firebase.initializeApp(firebaseConfig);</pre><p>Note: The above configuration can be found from your Firebase project(Under <strong><em>Project Settings</em></strong> or <strong><em>Step 8</em></strong>). Inside this file, we will integrate the cloud messaging. But before jumping in, we need a key called <strong><em>VALID</em></strong> key</p><p><strong>VALID key</strong><br>The key can be either generated or imported from your existing key pair through the Firebase console.<br>i. Open the <a href="https://console.firebase.google.com/project/_/settings/cloudmessaging">Cloud Messaging</a> tab of the Firebase console <strong><em>Settings</em></strong> pane and scroll to the <strong><em>Web configuration</em></strong> section.<br>ii. In the <strong><em>Web Push certificates</em></strong> tab, copy the <strong><em>Key pair</em></strong> (LHS Value in the screenshot below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulEqK4NoP0I5l4QWqJnlOQ.png" /></figure><p>Now, back to our<strong> firebaseinit.js</strong> file. Add the following lines of code:</p><pre>const messaging = firebase.messaging();<br>const { REACT_APP_VALID_KEY } = process.env<br>const publicKey = REACT_APP_VALID_KEY;</pre><p><strong>Permission for Notification</strong><br>Before sending push notifications to the browser, we first need to get permission from the user. This is handled by the getToken method that firebase provides.</p><pre>export const getToken = async (setTokenFound) =&gt; {<br>  let currentToken = &#39;&#39;;<br>  try {<br>    currentToken = await messaging.getToken({validKey: publicKey});<br>    if (currentToken) {<br>      setTokenFound(true);<br>    } else {<br>      setTokenFound(false);<br>    }<br>  } catch (error) {<br>    console.log(&#39;An error occurred while retrieving token.&#39;, error);<br>  }<br>  return currentToken;<br>};</pre><p><strong><em>getToken</em></strong> method will ask the user for notification permission in browsers, if it’s not granted. Otherwise, it will return a token or reject the permission due to an error. And we pass the valid key from the previous step to <strong><em>getToken</em></strong><br>After you’ve obtained the token, store it using your preferred method, in our case,<em> </em><strong><em>we will just log in the console</em></strong><em>.</em></p><p><strong>Set the Listeners</strong> <strong>for Foreground and Background</strong></p><p>When the app is active in <strong>foreground</strong>, we need to add this code to the firebaseInit.js file, so that we know the notification has received</p><pre>export const onMessageListener = () =&gt;<br>  new Promise((resolve) =&gt; {<br>    messaging.onMessage((payload) =&gt; {<br>      resolve(payload);<br>    });<br>  });</pre><p><strong>Background Listener</strong></p><p>In the scenario when the page is in background or hidden behind other tabs, we need to handle onBackgroundMessage.</p><ul><li>We do that by adding a firebase-messaging-sw.js <strong>service-worker</strong> file in the public folder of our react app. Add the following lines</li></ul><pre>importScripts(&quot;https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js&quot;);<br>importScripts(&quot;https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js&quot;);</pre><pre>const firebaseConfig = {<br>  apiKey: &quot;YOUR_API_KEY&quot;,<br>  authDomain: &quot;YOUR_AUTH_DOMAIN&quot;,<br>  projectId: &quot;YOUR_PROJECT_ID&quot;,<br>  storageBucket: &quot;YOUR_STORAGE_BUCKET&quot;,<br>  messagingSenderId: &quot;YOUR_MESSAGING_SENDER_ID&quot;,<br>  appId: &quot;YOUR_APP_ID&quot;,<br>  measurementId: &quot;YOUR MEASUREMENT ID&quot;<br>};firebase.initializeApp(firebaseConfig);</pre><p>The first two import statements basically download the firebase libraries required for the service worker.</p><p>Now you can use<strong><em> onMessageListener()</em></strong> method to get the notifications.</p><pre>onMessageListener()<br>    .then((payload) =&gt; {<br>      setShow(true);<br>      setNotification({<br>        title: payload.notification.title,<br>        body: payload.notification.body,<br>      });<br>      console.log(payload);<br>    })<br>    .catch((err) =&gt; console.log(&quot;failed: &quot;, err));</pre><p><strong><em>onMessageListener()</em></strong> function is invoked whenever we receive a message. You can however store the notification and display it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*A6COKsUqvKtHm92G4Sa6Bg.png" /></figure><p><strong>Testing the Notification</strong></p><p>Start your react project with,</p><pre>npm start<br>   or<br>yarn start</pre><p>Now, run your go server using <strong><em>go run main.go </em></strong>command, which will give you a success message and you will receive the notification in your react app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*W-LOE6MD473pSS22oS1AjA.png" /><figcaption>Running the backend server</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*-AFnmgL8VUeJf94EhJnPig.png" /><figcaption>Receiving notification in foreground</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*tuqGxrf55uFqOZyqkUdF6A.png" /><figcaption>Receiving notification in background</figcaption></figure><p><strong>Notification not appearing on your browser</strong><br>If you are not getting the notification and getting permission issues for notification in console that must be because notifications are not set to <strong>Allow. </strong>You can change the notification access to allow from block as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*Ya7PL-uiAdjh1gK1UgwF9A.png" /><figcaption>Not receiving notification in browser</figcaption></figure><p>That is how you can integrate Firebase push notification in Golang.<br>You can checkout the source code for backend here <a href="https://github.com/Prakash171999/push-notification">https://github.com/Prakash171999/push-notification</a></p><p>Happy coding 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b52910923988" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/push-notification-with-firebase-go-and-react-b52910923988">Push notification with firebase, Go and React</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>