<?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 Ayberk Dikcinar on Medium]]></title>
        <description><![CDATA[Stories by Ayberk Dikcinar on Medium]]></description>
        <link>https://medium.com/@ayberkdikcinar?source=rss-d3219be2090------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XV0RnHT8KDMBT6EC</url>
            <title>Stories by Ayberk Dikcinar on Medium</title>
            <link>https://medium.com/@ayberkdikcinar?source=rss-d3219be2090------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:43:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayberkdikcinar/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[Preventing Layout Shifts When Opening a Modal in React]]></title>
            <link>https://blog.devgenius.io/preventing-layout-shifts-when-opening-a-modal-in-react-fbe2b196858d?source=rss-d3219be2090------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbe2b196858d</guid>
            <category><![CDATA[dialog]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[modal]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ayberk Dikcinar]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 17:06:58 GMT</pubDate>
            <atom:updated>2025-03-22T01:11:13.832Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preventing Layout Shifts When Opening a Dialog(Modal) in React</h3><p>Let’s say you’re building a React app, and you want to show a modal dialog. When the modal opens, you want to prevent the rest of the page (the background) from being scrollable. A common approach is to set overflow: hidden on the body element when the modal is open:</p><pre>useEffect(() =&gt; {<br>  if (isOpen) {<br>    document.body.style.overflow = &#39;hidden&#39;;<br>  } else {<br>    document.body.style.overflow = &#39;auto&#39;; <br>  }<br>  return () =&gt; {<br>    document.body.style.overflow = &#39;auto&#39;;<br>  };<br><br>}, [isOpen]);</pre><p>While this works to disable scrolling, it introduces a new problem: <strong>layout shifts</strong>. When the scrollbar disappears, the page content suddenly shifts to the right to fill the space previously occupied by the scrollbar. This creates a bad user experience.</p><p>To prevent layout shifts, we need to <strong>reserve space for the scrollbar</strong> even when it’s hidden. This can be achieved by dynamically calculating the scrollbar size and applying padding to the body equal to the scrollbar width.</p><p><strong>First</strong>, create a function to dynamically calculate the scrollbar width:</p><pre>const getScrollbarWidth = () =&gt; {<br>  const outer = document.createElement(&#39;div&#39;);<br>  outer.style.visibility = &#39;hidden&#39;;<br>  outer.style.overflow = &#39;scroll&#39;;<br>  document.body.appendChild(outer);<br><br>  const inner = document.createElement(&#39;div&#39;);<br>  outer.appendChild(inner);<br><br>  const scrollbarWidth = outer.offsetWidth - inner.offsetWidth;<br><br>  outer.parentNode?.removeChild(outer);<br><br>  return scrollbarWidth;<br>};</pre><p>When the modal opens, calculate the scrollbar width and apply it as <strong><em>paddingRight</em></strong><em> </em>to the <strong><em>body</em></strong>. This reserves space for the scrollbar, preventing layout shifts:</p><pre>  useEffect(() =&gt; {<br>    if (isOpen) {<br>      const scrollWidth = getScrollbarWidth();<br>      document.body.style.overflow = &#39;hidden&#39;;<br>      document.body.style.paddingRight = `${scrollWidth}px`;<br>    } else {<br>      document.body.style.overflow = &#39;auto&#39;;<br>      document.body.style.paddingRight = `0`;<br>    }<br>    return () =&gt; {<br>      document.body.style.overflow = &#39;auto&#39;;<br>      document.body.style.paddingRight = `0`;<br>    };<br>  }, [isOpen]);</pre><p>This approach works across all devices and browsers, making it a reliable solution for your React apps.</p><p>Thanks for reading! Until next time, happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbe2b196858d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/preventing-layout-shifts-when-opening-a-modal-in-react-fbe2b196858d">Preventing Layout Shifts When Opening a Modal in React</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SALTSTACK QUICKSTART]]></title>
            <link>https://blog.devgenius.io/saltstack-quickstart-aafbfeda4934?source=rss-d3219be2090------2</link>
            <guid isPermaLink="false">https://medium.com/p/aafbfeda4934</guid>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[saltstack]]></category>
            <dc:creator><![CDATA[Ayberk Dikcinar]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 14:50:43 GMT</pubDate>
            <atom:updated>2024-01-19T15:59:59.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGo2Vra27xlmAfcmkjIjHQ.png" /></figure><p>Hey Everyone! In this article, we’re diving into the world of SaltStack, an awesome tool that makes managing servers and configurations a breeze. We’ll cover installation, configuration and the basics of Salt. Let’s jump right in!</p><h3>What is SaltStack?</h3><p>SaltStack, or simply Salt, is a configuration management and orchestration tool like Ansible. It helps you provision servers, manage existing ones, and install software across various IT environments, whether they’re physical servers, virtual machines, as well as the cloud.</p><p>Key Concepts:</p><ul><li><strong>Minion:</strong> The cool agent running on managed servers.</li><li><strong>Master: </strong>The wise server in control of those Minions.</li><li><strong>Grains:</strong> Tidbits of system info collected by Minions, like OS, IP, and more.</li><li><strong>States:</strong> Declarative descriptions of system configuration.</li><li><strong>Pillar:</strong> Secret sauce for storing sensitive info and configurations.</li></ul><h3>Installation</h3><p>Installing SaltStack is a piece of cake! Just follow <a href="https://docs.saltproject.io/salt/install-guide/en/latest/topics/install-by-operating-system/index.html">this guide</a> for your OS.</p><p>I will use 3 machines (AWS ec2 instances, os:RHEL) that are in the same network. One of them will be the master and the rest will be the minions with different minion_ids. For the minions, I am going to use 2 instances and while I setup them, I will assign minion_ids as ‘<strong>web01</strong>’ and ‘<strong>db01</strong>’.</p><p>Note that, you can also configure multiple masters for high availability and fault tolerance. However, just for the simplicity, we are going to use only 1 master.</p><pre># Master setup script<br>sudo rpm - import https://repo.saltproject.io/salt/py3/redhat/9/x86_64/SALT-PROJECT-GPG-PUBKEY-2023.pub <br>curl -fsSL https://repo.saltproject.io/salt/py3/redhat/9/x86_64/latest.repo | sudo tee /etc/yum.repos.d/salt.repo <br>sudo yum install -y salt-master <br>sudo systemctl enable salt-master &amp;&amp; sudo systemctl start salt-master</pre><pre># Minion setup script (foreach minion)<br>sudo rpm --import https://repo.saltproject.io/salt/py3/redhat/9/x86_64/SALT-PROJECT-GPG-PUBKEY-2023.pub<br>curl -fsSL https://repo.saltproject.io/salt/py3/redhat/9/x86_64/latest.repo | sudo tee /etc/yum.repos.d/salt.repo<br>sudo yum install -y salt-minion <br>echo &quot;master: 172.68.53.15&quot; | sudo tee /etc/salt/minion.d/master.conf<br>echo &quot;&lt;your_minion_id&gt;&quot; | sudo tee /etc/salt/minion_id<br>sudo systemctl enable salt-minion &amp;&amp; sudo systemctl start salt-minion<br><br># Quick Note: &quot;&lt;your_minion_id&gt;&quot; part is just giving id to the minion.<br># Quick Note: &quot;172.68.53.15&quot; is the private ip of my master server.</pre><h3>Setup</h3><p><strong>Managing the minions from the master;</strong></p><p>For this, you should use salt-key command. salt-key provides you to list, accept, reject, delete the minions that are available. After setup, just ssh to your master and become the superuser (sudo su) to use these commands.</p><p>· List: salt-key -l &lt;status&gt; or -L for ALL without status. (status can be un, acc, rej) un: unaccepted, acc: accepted, rej: rejected</p><p>· Accept: salt-key &lt;minion_id&gt; -a</p><p>· Reject: salt-key &lt;minion_id&gt; -r</p><p>· Delete: salt-key &lt;minion_id&gt; -d</p><p><strong>Note that;</strong> for accepting, rejecting, deleting <strong>ALL</strong> use upper case version of the flag. As an example; -A, -R, -D, -L</p><p>If your setup is correct, you sould be able to see ‘web01’ and ‘db01’ instances as unaccepted. Let’s accept;</p><pre>salt-key &#39;web01&#39; -a<br>salt-key &#39;db01&#39; -a<br># check it is accepted successfully.<br>salt-key -l acc<br># Test minion connectivity (&#39;*&#39; stands for all minions) <br>salt &#39;*&#39; test.ping<br># if web01, db01 in the list, and the ping results are true, well done!</pre><p>So far, we have created instances and did the installation &amp; setup for connections. Lets continue with the pillar &amp; grains.</p><h3>Grains &amp; Pillars</h3><p><strong>Grains:</strong> Grains works for gathering static information about a minion, such as operating system details, hardware information, IP addresses, and more.</p><p><strong>Pillars: </strong>Pillars are a powerful feature that allows you to securely and dynamically manage configuration data for your infrastructure. Pillars are used to store sensitive and dynamic information such as passwords, API keys, and other configuration details. Unlike grains, pillars are designed to hold data that might change frequently or needs to be kept confidential.</p><p>Basic Grains commands;</p><pre># Available grains list.<br>salt &lt;minion_selection&gt; grains.ls<br># Grains information.<br>salt &lt;minion_selection&gt; grains.items <br># Refresh the grains.<br>salt &lt;minion_selection&gt; saltutil.refresh_grains <br># Manipulate the values of the grains (You can also do it programmitacally)<br>salt &lt;minion_selection&gt; grains.setval &lt;key&gt; &lt;value&gt;<br>salt &lt;minion_selection&gt; grains.delval &lt;key&gt; &lt;value&gt;<br>Examples: <br>salt &#39;web*&#39; grains.setval &#39;environment&#39; &#39;dev&#39; #add a grain value.<br>salt &#39;web*&#39;  grains.setval &#39;roles&#39; [&#39;web&#39;, &#39;app1&#39;, &#39;dev&#39;] #add multiple values<br>salt &#39;web01&#39; grains.delval &#39;environment&#39; #delete a grain value.<br><br>And more, you can also use grain information for targeting the minions.<br>Target by grains: <br>• sudo salt -G &#39;os:Ubuntu&#39; test.ping<br>• salt -G &#39;cpuarch:x86_64&#39; grains.item num_cpus<br>#(grains that are nested in a dictionary can be matched by adding a colon for each level that is traversed.)<br>• salt -G &#39;ec2_tags:environment:*production*&#39; <br></pre><p>Basic Pilars commands;</p><pre>#gather pillar information.<br>salt &lt;minion_selection&gt; pillar.items<br>#refresh the pillars.<br>salt &lt;minion_selection&gt; saltutil.pillar_refresh <br></pre><h3>Roots - Where Salt Looks for SLS Files</h3><ul><li>Roots are directories where Salt looks for SLS files.</li><li>They are defined in the Salt master configuration file, usually located at /etc/salt/master.d/roots.conf</li><li>Roots can be organized into environments such as base, dev, prodor qa</li></ul><p>Example roots.conf:</p><pre>file_roots: #state file locations<br>  base:<br>    - /srv/salt/base<br>  dev:<br>    - /srv/salt/dev<br>  qa:<br>    - /srv/salt/qa<br>pillar_roots: #pillar locations<br>  base:<br>    -/srv/salt/pillars/base<br>  dev:<br>    -/srv/salt/pillars/dev<br>  qa:<br>    -/srv/salt/pillars/qa<br><br>#Feel free to adapt the environment names and directory paths<br>#based on your organizational or project requirements.</pre><h3>State Files — The Blueprint of Configuration</h3><p>SaltStack state files are the heart of your configuration management. They are written in YAML and define the desired state of the system.</p><ul><li>The purpose of state file is to keep that data on file and not have to re-run them one by one via cli.</li><li>State files are organized into .sls (SaltStack State) files.</li><li>Each SLS file represents a specific configuration or set of actions (<a href="https://docs.saltproject.io/en/latest/ref/modules/all/index.html">using salt modules</a>) to be applied to minions.</li><li>Grain and pillars can be used on a state file for conditional module execution.</li></ul><p>Example state file;</p><pre># /srv/salt/base/apache/init.sls<br>install_apache:<br>  pkg.installed:<br>    - name: apache2</pre><p>In this example, the state file init.sls installs the Apache package on minions. You can use grains and pillars in state files to conditionally execute specific configurations based on minion characteristics.</p><p><strong>Note:</strong> init is the default name for the state file which means each state needs init.sls (You can change it, however I will recommend you to use init)</p><p>For targeting specific minions for state files, top.sls files comes in play.</p><h3>Top files</h3><ul><li>Defines the salt environment.</li><li>Aggregates a list of minions and runs a list of states in the declared order or lexical order.</li><li>Syncs grains, pillars, and states before running.</li><li>Merge multiple environments to run large list of states.</li></ul><p>It is named as <strong>‘top’</strong> cause it stands on the top of the state files (Like init, it is also default name for the top files, I dont recommend you to change it)</p><p>Here is the example <strong>folder structure</strong>;</p><pre>├── dev<br>│   ├── users<br>│   │   └── init.sls<br>│   ├── apache<br>│   │   └── init.sls<br>│   ├── postgresql<br>│   │   ├── init.sls<br>│   ├── top.sls<br>├── qa<br>│   ├── users<br>│   │   └── init.sls<br>│   ├── apache<br>│   │   └── init.sls<br>│   ├── postgresql<br>│   │   ├── init.sls<br>│   │── top.sls<br>├── base<br>│   ├── users<br>│   │   └── init.sls<br>│   ├── apache<br>│   │   └── init.sls<br>│   ├── postgresql<br>│   │   ├── init.sls<br>│   │── top.sls</pre><p>Note that, you can also merge the top files into one top.sls. (I do not recommend)</p><p>Example top file;</p><pre>dev:<br>  &#39;db*&#39;:<br>    - users <br>    - postgresql <br>  &#39;web*&#39;:<br>    - apache<br><br># dev represents the environment.<br><br># &#39;db*&#39; and &#39;web*&#39; provide us to target the instances based on their id&#39;s.<br># which means run the apache state only for the instances which has id starts with web.<br><br># users, postgresql, apache: these are the names of the states.<br># each one located in another folder under /dev/users /dev/postgresql /dev/apache<br># and each one has init.sls like /dev/users/init.sls</pre><h3>Apply the states</h3><p>Okey, we did the configurations, we wrote the state files and top files. These files must be located in the path you defined in the roots.conf (Very important)</p><p><strong>Note:</strong> I did not provide the contents of the states files in deep. So, you can find examples from the <a href="https://docs.saltproject.io/en/latest/contents.html">salt documentation</a>.</p><p><strong>To see is what is gonna be applied to the state</strong></p><pre>#They do not apply any changes to the system<br>#but gives you a detailed look at the compiled state data.<br><br>salt &#39;*&#39; state.show_highstate #more detailed<br>salt &#39;*&#39; state.show_lowstate #less detailed<br>salt &#39;*&#39; state.show_low_sls &lt;state_selection&gt; #less detailed with specific state selected.</pre><p><strong>Apply</strong></p><pre>#without show_<br>salt &#39;*&#39; state.highstate #apply the states<br>#or<br>salt &#39;*&#39; state.apply<br>#calling state.apply with no arguments starts a highstate.</pre><p>Lastly, I didn’t mention about jinja and kitchenSalt to avoid making the article too long, but if you’re curious about how to test or how to write SLS files programmatically, here is the links that might want to dive into.</p><ul><li><a href="https://github.com/saltstack/kitchen-salt/tree/master">Salt Kitchen</a></li><li>J<a href="https://docs.saltproject.io/salt/user-guide/en/latest/topics/jinja.html">inja</a></li></ul><p>And there you have it! We’ve just scratched the surface of SaltStack. If you found this guide helpful, I’m delighted. Thanks for joining the Salt adventure with me and stay tuned for the next articles. Happy readings!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aafbfeda4934" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/saltstack-quickstart-aafbfeda4934">SALTSTACK QUICKSTART</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS (Typescript) Authentication Service with Amazon Cognito User Pools]]></title>
            <link>https://blog.devgenius.io/nodejs-typescript-authentication-service-with-amazon-cognito-user-pools-9a12ea066ffb?source=rss-d3219be2090------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a12ea066ffb</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[cognito-user-pools]]></category>
            <category><![CDATA[cognito]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Ayberk Dikcinar]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 13:58:13 GMT</pubDate>
            <atom:updated>2023-07-12T14:33:44.691Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, in this article, we will look at how to use amazon cognito as authentication provider for our backend app that is written in typescript and expressjs framework. Let’s start without talking too much :)</p><h3>What is Amazon Cognito</h3><p>Amazon Cognito is an AWS service that provides authentication, authorization, and user management for web and mobile applications. It offers two main components: User Pools and Identity Pools, both aimed at addressing different aspects of identity solution needs.</p><h4>User Pools</h4><p>User Pools act as a user directory, providing a secure and scalable solution for user sign up and sign in. User Pools support user registration and authentication with standard attributes for each user.</p><p>They also allow you to customize sign-in flows, integrate social media and email/phone-based logins, use multi-factor authentication (MFA), and maintain compliance requirements via user pool add-on features. Users can sign in directly into a User Pool, or indirectly via Identity Providers (IdP) like Facebook, Google, Amazon, or a SAML-based identity provider.</p><h4>App Clients</h4><p>In the context of User Pools, App Clients are important entities. When you configure an App Client, you’re enabling a frontend &amp; backend application (like a web app, a mobile app, or a server-side application) to interact with your User Pool.</p><p>Each App Client has its own configuration settings for things like OAuth 2.0 flows, scopes, and a callback URL for redirecting users after they authenticate. An App Client also has a client ID and an optional client secret that you use when configuring the application.</p><p>In our example, we do not use any frontend instead we will use server-side application to manage the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*Uu9hqecWHmzCkvKSSDq2GA.png" /><figcaption>Authentication flow</figcaption></figure><p><strong>Id Token vs Access Token vs Refresh Token</strong></p><p>Amazon Cognito returns three tokens after a successful sign-in: an ID token, an access token, and a refresh token. Each of these tokens serves a different purpose:</p><ol><li><strong>ID Token:</strong> This is a JSON Web Token (JWT) that contains claims about the identity of the authenticated user such as name, email, and phone number. It can be used to extract user profile information after a successful authentication. The ID token is used by your application to confirm that the user who claims to be authenticated is indeed the authenticated user.</li><li><strong>Access Token:</strong> This is also a JWT that is used for authorization to access specific resources. It grants permissions that allow the user to access server-side resources. It contains scopes and groups and does not typically contain user information. In the context of Amazon Cognito, the access token authorizes the user to access the resources enabled by Amazon Cognito and AWS Identity and Access Management (IAM).</li><li><strong>Refresh Token:</strong> This is used to get new ID and access tokens. It’s provided for situations where the current ID and access tokens have expired and need to be refreshed. The refresh token has a longer expiration time compared to the ID and access tokens.</li></ol><p>Here is the screenshots for both idToken and accessToken payload;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0iU3BM2-N_b5gLHm-MLsg.png" /><figcaption>ACCESSTOKEN</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dezY1wnhwCku90FpPVSaHA.png" /><figcaption>IDTOKEN</figcaption></figure><p>You can see the differences between these two tokens above. Anyway…</p><h3>Lets Dive In :)</h3><ol><li>Create a cognito user pool on AWS Console. Here is the link that guides you <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html">https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html</a></li><li>Create an application client under the user_pool and enable ALLOW_USER_PASSWORD_AUTH (It provide us ability to sign in with our username and password to the application). And do not forget to enable client_secret. Here is the link that guides you <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html">https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html</a></li><li>Create a new app with npm init and install the dependencies for our server-app.</li></ol><p>Here is the list of dependencies:</p><pre>express<br>@types/express<br>body-parser<br>@aws-sdk/client-cognito-identity-provider<br>jsonwebtoken<br>@types/jsonwebtoken<br>jwks-rsa<br>ts-node-dev<br>typescript</pre><p>Under the scripts inside package.json, add “start”: “ ts-node-dev src/index.ts”</p><p>4. Application codes</p><p>First of all, we are going to start with the cognito.service implementation. For adding new users to the user Pool, does not require any aws credentials. We only need region, userPoolId, clientId and client secret(secretHash).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db1deefa9b2fce0c1c84b95d33473c65/href">https://medium.com/media/db1deefa9b2fce0c1c84b95d33473c65/href</a></iframe><p>Here is the express middleware function that validates the token and assigns the user to the Request. (request.user)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87dd9211d44b8813295c85f4d24df61d/href">https://medium.com/media/87dd9211d44b8813295c85f4d24df61d/href</a></iframe><p>Here is the middleware that checks the request.user</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbfeabb4123f70b0daea34ce3e846abd/href">https://medium.com/media/bbfeabb4123f70b0daea34ce3e846abd/href</a></iframe><p>Here are the express routers for signin, signup and current-user :)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/316db16f3e386a9740cb60813fd2699a/href">https://medium.com/media/316db16f3e386a9740cb60813fd2699a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18ab31cfae143c5410ae71051be7c697/href">https://medium.com/media/18ab31cfae143c5410ae71051be7c697/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bec34f2a654b0b4eaace147d3a59c53/href">https://medium.com/media/7bec34f2a654b0b4eaace147d3a59c53/href</a></iframe><p>And finally, our index file;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84a1a48c7bbb178d74c70bc202445f5d/href">https://medium.com/media/84a1a48c7bbb178d74c70bc202445f5d/href</a></iframe><p>In a nutshell, that’s the story of Amazon Cognito! I hope I’ve been able to provide some valuable insights and information. Thank you for taking the time to read, and I look forward to catching up with you in my next piece. Until then, happy coding and see you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a12ea066ffb" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/nodejs-typescript-authentication-service-with-amazon-cognito-user-pools-9a12ea066ffb">NodeJS (Typescript) Authentication Service with Amazon Cognito User Pools</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is GraphQL and How to Implement it using ExpressJS?]]></title>
            <link>https://blog.devgenius.io/what-is-graphql-and-how-to-implement-it-using-expressjs-53c006d86d34?source=rss-d3219be2090------2</link>
            <guid isPermaLink="false">https://medium.com/p/53c006d86d34</guid>
            <category><![CDATA[graphql-schema]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Ayberk Dikcinar]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 22:03:11 GMT</pubDate>
            <atom:updated>2023-07-12T14:34:14.881Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we are going to discuss what GraphQL is, its differences from REST API, and how to implement it using Express.js.</p><p>GraphQL is a query language and runtime. It enables clients to communicate with APIs and retrieve the precise data they need from a server. GraphQL follows a different approach compared to REST APIs.</p><h4><strong>Here are some prominent differences between GraphQL and REST API:</strong></h4><p><strong>Flexibility:</strong> GraphQL allows clients to specify the exact data they require. Clients can query specific fields and related data, eliminating over-fetching or under-fetching of data and optimizing network usage.</p><p><strong>Single Request Structure:</strong> Unlike REST APIs, where clients often make multiple requests to various endpoints, GraphQL enables clients to fetch multiple data points in a single request. For example, in a blog application, you can request both the list of blog posts and their respective authors in one GraphQL query.</p><p><strong>Shaping Data: </strong>GraphQL gives clients control over the shape of the data they receive. Clients can request specific fields, nested data, and even specify the format of the response (such as JSON or XML). This provides a more tailored and efficient data exchange mechanism.</p><p><strong>Innovative Query Language:</strong> GraphQL provides a rich query language. Clients can query multiple resources, access deeply nested data, perform filtering, sorting, and pagination operations, making data retrieval more flexible and powerful.</p><h4><strong>Now, let’s briefly discuss how GraphQL works:</strong></h4><p><strong>Schema Definition:</strong> In GraphQL, you start by defining a schema, which describes the available data and operations. The schema consists of types and fields that define the structure of the data accessible to clients.</p><p><strong>Query Composition: </strong>Clients construct GraphQL queries to request the specific data they need. Queries are written according to the schema and can include desired fields, filters, and other parameters.</p><p><strong>Mutation Operations:</strong> In addition to queries, GraphQL also supports mutations, which are used to modify data on the server. Clients can perform create, update, or delete operations using a similar syntax to queries.</p><p><strong>Query Interpretation:</strong> When a GraphQL query reaches the server, it interprets the query based on the schema. Resolver functions are used to gather and process the relevant data for each field specified in the query.</p><p><strong>Data Response: </strong>Once the resolver functions have executed, the server assembles the response according to the requested fields. The matched data is packaged and sent back to the client in a structured format.</p><p>Through this process, GraphQL allows clients to fetch precisely the data they require and perform mutations to modify data on the server. Servers can efficiently serve the requested data and handle mutations in a controlled manner.</p><h4><strong>Implementation GraphQL server using ExpressJS</strong></h4><p>We have discussed what GraphQL is, its differences compared to REST API, and other aspects. Now, it’s time to dive into coding.</p><p>Firstly, we need some packages to install.</p><pre>npm install express express-graphql @graphql-tools/load-files @graphql-tools/schema</pre><ol><li>“@graphql-tools/load-files”: This package provides a utility for loading GraphQL files from a specified directory. It allows you to load GraphQL type definitions and resolver functions from multiple files and directories, making it easier to organize and modularize your GraphQL schema.</li><li>“@graphql-tools/schema”: This package provides tools for building and manipulating GraphQL schemas. It includes functions for merging multiple GraphQL schemas, generating a schema from GraphQL type definitions, and other schema-related operations. It helps simplify the process of creating and managing GraphQL schemas in your application.</li><li>“express-graphql” This package provides an integration layer between Express.js and GraphQL, allowing you to easily create a GraphQL API endpoint in your Express.js application.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a34709322bc2f85fea8d325352d5df3/href">https://medium.com/media/4a34709322bc2f85fea8d325352d5df3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7946401f67e027a46fc89e0569e9095/href">https://medium.com/media/e7946401f67e027a46fc89e0569e9095/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/619dec86cf07f391a29462f7f7eebf0f/href">https://medium.com/media/619dec86cf07f391a29462f7f7eebf0f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/296616d9d6c6e4aeef5a58fc46a9d2bc/href">https://medium.com/media/296616d9d6c6e4aeef5a58fc46a9d2bc/href</a></iframe><p>Above file appears to define a GraphQL schema, which specifies the structure and behavior of an API. It includes set of queries and mutations for managing orders, products, and reviews. It allows you to retrieve orders and products, add new products and reviews, and perform various operations related to these entities in a GraphQL API.</p><p>Note that, in GraphQL, ID is a built-in scalar type that represents a unique identifier. It is often used to identify and retrieve specific objects in the API. The ID type can be represented as a string or an integer.</p><p>The ! symbol in the schema denotes a non-null type modifier. It is used to indicate that a field or argument must always have a value and cannot be null. For example, id: ID! means that the id field or argument is required and must be provided with a non-null value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4084e70ef025f9051d0070232b8a881f/href">https://medium.com/media/4084e70ef025f9051d0070232b8a881f/href</a></iframe><p>Above file exports resolver functions that connect the GraphQL schema with the underlying data models. These resolvers execute the necessary logic by calling the appropriate functions from the models and return the results to fulfill the GraphQL queries and mutations.</p><p>Note that, the args parameter contains the arguments provided in the GraphQL query for the current field. These arguments allow you to customize the behavior of the resolver function and fetch specific data based on the provided values.</p><h4>Examle Queries &amp; Mutations</h4><p>As a quick note, If you set optiongraphiql: true, you will be greeted with an interface at the /graphql (GET) endpoint where you can perform queries. It is a great interface for testing the graphql API you have written.</p><p>Here are some example queries &amp; mutations…</p><pre>//Retrieve all orders<br>query {<br>  orders {<br>    id<br>    date<br>    totalPrice<br>    items {<br>      item {<br>        id<br>        description<br>        reviews {<br>          comment<br>          rating<br>        }<br>        price<br>      }<br>      quantity<br>    }<br>  }<br>}<br><br>//Retrieve an order by ID<br>query {<br>  orderById(id: &quot;123&quot;) {<br>    id<br>    date<br>    totalPrice<br>    items {<br>      item {<br>        id<br>        description<br>        reviews {<br>          comment<br>          rating<br>        }<br>        price<br>      }<br>      quantity<br>    }<br>  }<br>}<br><br>//Retrieve all products<br>query {<br>  products {<br>    id<br>    description<br>    reviews {<br>      comment<br>      rating<br>    }<br>    price<br>  }<br>}<br><br>//Retrieve a product by ID<br>query {<br>  productById(id: &quot;456&quot;) {<br>    id<br>    description<br>    reviews {<br>      comment<br>      rating<br>    }<br>    price<br>  }<br>}<br><br>//Retrieve products within a price range<br>query {<br>  productsByPrice(min: 10.0, max: 50.0) {<br>    id<br>    description<br>    reviews {<br>      comment<br>      rating<br>    }<br>    price<br>  }<br>}<br><br>//Add a new product<br>mutation {<br>  addNewProduct(id: &quot;789&quot;, description: &quot;New Product&quot;, price: 29.99) {<br>    id<br>    description<br>    reviews {<br>      comment<br>      rating<br>    }<br>    price<br>  }<br>}<br><br>//Add a new review for a product<br>mutation {<br>  addNewReview(productId: &quot;456&quot;, comment: &quot;Great product!&quot;, rating: 5) {<br>    comment<br>    rating<br>  }<br>}</pre><p>Thanks for your valuable time, I encourage you to search for <a href="https://www.apollographql.com/">Apollo</a> project. I sincerely hope it has been helpful. Looking forward to connecting again in future articles :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53c006d86d34" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/what-is-graphql-and-how-to-implement-it-using-expressjs-53c006d86d34">What is GraphQL and How to Implement it using ExpressJS?</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Ingress With Nginx]]></title>
            <link>https://blog.devgenius.io/kubernetes-ingress-with-nginx-975e6867c617?source=rss-d3219be2090------2</link>
            <guid isPermaLink="false">https://medium.com/p/975e6867c617</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[ingress]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ayberk Dikcinar]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 00:14:48 GMT</pubDate>
            <atom:updated>2022-11-28T08:40:39.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*zGTiR1_UfGgAyTs_ti5gVA.png" /><figcaption>Basic Architecture</figcaption></figure><p>Hello, In this article we ‘re going to take a look at kubernetes ingress nginx controller.</p><p>Ingress is a solution that provide us to direct external traffic to kubernetes services in the cluster.</p><p>Ingress nginx controller works on layer 7 that means it gives us a opportunity to do <strong>path based routing</strong>. If we don’t use ingress, we need to use a separate loadbalancer for each application, which is difficult to manage, which is another part that makes ingress beautiful.</p><p><strong>If you want to know how ingress works, you can check:</strong> <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/">https://kubernetes.io/docs/concepts/services-networking/ingress/</a></p><p><strong>To install ingress nginx controller, please go here:</strong> <a href="https://kubernetes.github.io/ingress-nginx/deploy/">https://kubernetes.github.io/ingress-nginx/deploy/</a></p><p>When you install ingress-nginx, it creates a namespace to put objects that are created by it. Nginx is actually an application which should be running in the cluster. Thats why it deploys a deployment object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WzKk6jAkM6KHQEU7WT76VA.png" /><figcaption>Objects that are created by ingress-nginx</figcaption></figure><p>As you can see, ingress-nginx-controller creates a loadBalancer service that listens localhost 80 and 443 ports.</p><p>If you have installed the nginx ingress controller, lets start. If we look at the example architecture above, we need to create deployments and services first.</p><p><strong>Note: The images for the containers are just express applications that listens port 3000 which is not a big deal.</strong> Ticket app has get router for <strong>“/api/tickets/”</strong> and Order app has get router for <strong>“/api/orders/”</strong> and both response with simple ‘hello from &lt;app-name&gt;’.</p><p>Creating deployment and service objects for both ticket and order app;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ebe20bb7eb215b7062ea16a93aadece/href">https://medium.com/media/7ebe20bb7eb215b7062ea16a93aadece/href</a></iframe><pre>kubectl apply -f depl.yaml</pre><p>Creating ingress;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9076b17d0742d9d8fdeacfdf6855061a/href">https://medium.com/media/9076b17d0742d9d8fdeacfdf6855061a/href</a></iframe><pre>kubectl apply -f ingress-srv.yaml</pre><p>The host in the rules section is important, because you can host multiple domains inside one single kubernetes cluster. So that’s what this host property all about.</p><p>Cause of that specific domain property in the file, we can not reach the applications just by typing localhost on the browser. To access them, we are going to use a trick. So in other words, whenever we try to connect test.dev, it ‘ll connect to localhost rather than the real test.dev domain that is probably exist somewhere on the internet thanks to our trick.</p><p>To apply that trick, we ‘ll change the hosts configuration file inside our machine.</p><p>Locations for the host configuration file depending on OS;</p><pre>Windows: C:\Windows\System32\Drivers\hosts<br>Mac&amp;Linux: /etc/hosts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*jWQwSOUWFkEoXmXSMX1OuQ.png" /><figcaption>Add a definition for test.dev that is binded to localhost ip</figcaption></figure><p><strong>Quick note:</strong> If you are using minikube, you should use your minikube ip instead of 127.0.0.1 (To learn your minikube ip, just type ‘minikube ip’ to your terminal)</p><p>So lets try, open the browser and try to go <strong>test.dev/api/tickets</strong> and <strong>test.dev/api/orders</strong></p><p>If you see <strong>NOT SAFE</strong> page. Just type ‘thisisunsafe’ somewhere on the browser.</p><p>I hope its worked. Thanks for your precious time. See you in the next article :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=975e6867c617" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/kubernetes-ingress-with-nginx-975e6867c617">Kubernetes Ingress With Nginx</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOW TO DEPLOY REACT & GO PROJECT ON VPS USING NGINX]]></title>
            <link>https://blog.devgenius.io/how-to-deploy-react-go-project-on-vps-using-nginx-73df7930f85f?source=rss-d3219be2090------2</link>
            <guid isPermaLink="false">https://medium.com/p/73df7930f85f</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Ayberk Dikcinar]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 11:51:33 GMT</pubDate>
            <atom:updated>2023-01-30T15:39:38.508Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, In this article I will talk about how can you deploy a react project with backend that is written in Go Gin Framework.</p><p><strong>Prerequisites</strong></p><p>· Should have domain and subdomains. I am going to use test.com, api.test.com, admin.test.com in this article.</p><p>· Should bind your domains to your public IP. You can search for how to Add A Record.</p><p>· Should have VPS (Virtual Private Server that has Linux Ubuntu OS)</p><p>Lets look at the basic artchitecture first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*Aw9uvoErIg5FGwYuFMpZrw.png" /></figure><h3><strong>Steps</strong></h3><p><strong>1) Connect to VPS via SSH</strong></p><p>To connect your vps via ssh, you should open the port 22. It usually comes open by default (If not then go to your provider and open that port from the panel).</p><p><strong>2) Installing neccessary packages</strong></p><p>Install nginx, firewall, golang, npm and git.</p><pre>apt install nginx</pre><pre>apt install ufw</pre><pre>apt install golang-go</pre><pre>apt install nodejs  //(or apt install npm)</pre><pre>apt install git</pre><p><strong>3) Enable firewall</strong></p><pre>ufw enable</pre><pre>ufw allow ssh //<em>(dont forget. If you forget, you may not connect again to your vps 😊)</em></pre><pre>ufw allow “Nginx Full”</pre><pre>ufw status</pre><p><strong>4) Clone your projects into somewhere using git clone. </strong>(for our example they are client, admin-panel and backend)</p><p><strong>5) Remove the static html folder inside /var/www and create your folders.</strong></p><pre>rm -rf /var/www/html</pre><pre>mkdir /var/www/test/client //<em>(It ‘ll keep the build files for react client)</em></pre><pre>mkdir /var/www/test/admin-panel //<em>(It ‘ll keep the build files for react admin-panel)</em></pre><p><em>Note: We did not create a folder for the backend, because we dont need to publish any static file for it.</em></p><p><strong>6) Create build files and copy to /var/www</strong></p><p>Go to your project directory and run this command. I assume you ‘ve already run npm install to get dependent packages for the project.</p><pre><strong>---For Client---</strong><br>npm run build</pre><pre>cp -r build/* /var/www/test/client</pre><pre><strong>--For Admin Panel---</strong><br>npm run build</pre><pre>cp -r build/* /var/www/test/admin-panel</pre><p><strong>7) Configure nginx</strong></p><p>Firstly delete the default nginx configuration files. To do that;</p><pre>rm /etc/nginx/sites-available/default</pre><pre>rm /etc/nginx/sites-enabled/default</pre><p>Create your own file;</p><pre>nano /etc/nginx/sites-available/test</pre><p>Configure the nginx file;</p><pre>server {</pre><pre>listen 80;</pre><pre>server_name test.com www.test.com</pre><pre>location / {</pre><pre>root /var/www/test/client;</pre><pre>index  index.html index.htm;</pre><pre>proxy_http_version 1.1;</pre><pre>proxy_set_header Upgrade $http_upgrade;</pre><pre>proxy_set_header Connection &#39;upgrade&#39;;</pre><pre>proxy_set_header Host $host;</pre><pre>proxy_cache_bypass $http_upgrade;</pre><pre>try_files $uri $uri/ /index.html;</pre><pre>}<br>}</pre><pre>server {</pre><pre>listen 80;</pre><pre>server_name admin.test.com</pre><pre>location / {</pre><pre>root /var/www/test/admin-panel;</pre><pre>index  index.html index.htm;</pre><pre>proxy_http_version 1.1;</pre><pre>proxy_set_header Upgrade $http_upgrade;</pre><pre>proxy_set_header Connection &#39;upgrade&#39;;</pre><pre>proxy_set_header Host $host;</pre><pre>proxy_cache_bypass $http_upgrade;</pre><pre>try_files $uri $uri/ /index.html;</pre><pre>}<br>}</pre><pre>server {</pre><pre>listen 80;</pre><pre>server_name api.test.com</pre><pre>location / {</pre><pre>proxy_pass http://&lt;your-public-ip&gt;:&lt;backend-port&gt;;</pre><pre>proxy_http_version 1.1;</pre><pre>proxy_set_header Upgrade $http_upgrade;</pre><pre>proxy_set_header Connection &#39;upgrade&#39;;</pre><pre>proxy_set_header Host $host;</pre><pre>proxy_cache_bypass $http_upgrade;</pre><pre>}</pre><pre>}</pre><p>Link the sites-available and enabled files;</p><pre>ln -s /etc/nginx/sites-available/test /etc/nginx/sites-enabled/test</pre><p>Restart nginx;</p><pre>sudo systemctl restart nginx</pre><p>We ‘ve configured the nginx. Client and admin panel should be working at the moment. But how about our backend? We should keep it running. Of course you can do it manually by running main.go, but there is a way to do it defaultly when the machine starts.</p><p>We’ve set the port 8080 for our backend. Therefore your backend should be listening this port, but ofc you are free to change it as you wish.</p><p>To run your backend automatically, <strong>pm2</strong> is a good choice.</p><p>Firstly, lets install pm2 package <strong>globally</strong> using npm.</p><pre>npm install  -g pm2</pre><p>Now, go to your backend project directory and run this;</p><pre>pm2 start --name api “go run main.go”</pre><p>Set pm2 start-up;</p><pre>pm2 startup ubuntu</pre><p>As you know, our domain is not using SSL. If you want to active ssl certification; <em>(Do not forget to replace your backend urls from the clients as https://)</em></p><pre>apt install certbot python3-certbot-nginx<br>certbot --nginx -d test.com -d api.test.com -d admin.test.com</pre><p>Certificates are only valid for 90days. If you want to refresh them automatically, set a timer;</p><pre>systemctl status certbot.timer</pre><p>Annd, thats all! I hope its worked. Thank you for your time. If you have any questions feel free to contact me :) See you in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73df7930f85f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/how-to-deploy-react-go-project-on-vps-using-nginx-73df7930f85f">HOW TO DEPLOY REACT &amp; GO PROJECT ON VPS USING NGINX</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrent Programming In Golang]]></title>
            <link>https://blog.devgenius.io/concurrent-programming-with-golang-2a4edb2552b1?source=rss-d3219be2090------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a4edb2552b1</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[wait-groups]]></category>
            <dc:creator><![CDATA[Ayberk Dikcinar]]></dc:creator>
            <pubDate>Thu, 29 Sep 2022 15:51:22 GMT</pubDate>
            <atom:updated>2022-10-16T14:04:29.134Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! In this article, I will talk about the basic structures that we need to know in order to enable simultaneous, that is, more than one job, to be done at the same time in the Go language. Firstly let’s understand the difference between concurrency and parallelism breafly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOCsWxmdJIQEZelF1sp4WA.png" /></figure><p>Let’s take a look at how concurrency and parallelism work with the above example. As we can see, there are two cores and two tasks. In a concurrent approach, each core is executing both tasks by switching among them over time. In contrast, the parallel approach doesn’t switch among tasks, but instead executes them in parallel over time.</p><h3>Goroutines</h3><p>Thanks to the goroutines, we can enable more than one job to be done at the same time in our go program. In other words, the concept of goroutine can be summarized as each job done concurrently.</p><p>Every go program basically has a main goroutine which is formed together with the main function. However, the main goroutine alone may not be sufficient in some cases. For example, let’s say we have <em>save() </em>and <em>calculate()</em> functions that will take a long time. If these functions do not have a goroutine of their own, they use the main goroutine and keeps other processes waiting or waits that use the same goroutine. This is a situation that slows down the flow of the program and creates performance problems. To prevent that, we can run jobs concurrently by creating their own goroutines.</p><p>First, let’s examine the problem with the help of an example;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0750dc32dfb155b43a71ddba23ed1666/href">https://medium.com/media/0750dc32dfb155b43a71ddba23ed1666/href</a></iframe><pre>----------------Output----------------:</pre><pre>Saving... <br>The record has been saved - It took 5.0018482 <br>Calculating... <br>The calculation result:8 - It took 2.0019639 Total time: 7.0038452</pre><p>As can be seen in the output above, the save function worked and finished after 5 seconds. After that, the calculate function worked and finished in 2 seconds. However, if we look at it, the calculate function waited for the save function for 5 seconds and worked for 2 seconds, so it took 7 seconds in total.</p><p>The Go programming language uses the go keyword to create a goroutine and creates a separate goroutine for each job with the go keyword.</p><p>Let’s give it a try.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e97bfe7fb340c394249d733a6432e0e/href">https://medium.com/media/9e97bfe7fb340c394249d733a6432e0e/href</a></iframe><pre>----------------Output----------------:</pre><pre>Total time: 0</pre><p>A surprising result is that the total time is 0. This is because our go program creates different goroutines for the save and calculate functions, but terminates the program directly without waiting for them to finish.</p><p>If we delay the execution of the main function until the other goroutines are finished;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddb2f3ab64759047181fda56d40b33eb/href">https://medium.com/media/ddb2f3ab64759047181fda56d40b33eb/href</a></iframe><pre>----------------Output 1----------------:</pre><pre>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br>Saving...<br>Calculating...<br>The calculation result:8 - It took 2.0119652<br>The record has been saved - It took 5.0112932<br>Total time: 5.0112932</pre><pre>----------------Output 2----------------:</pre><pre>AAAASaving...<br>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA<br>Calculating...<br>The calculation result:8 - It took 2.017128<br>The record has been saved - It took 5.0123579<br>Total time: 5.0123579</pre><p><strong><em>In Output 1,</em></strong> first the printA function worked and finished. Then the save and calculate functions worked concurrently. The calculate function finished its job in 2 seconds, and the save function finished its job after 3 more seconds.</p><p><strong><em>In Output 2,</em></strong> first the printA function worked but not finished yet. Then the save function worked concurrently. Then the printA function finished and the calculate function started to work.</p><p><strong><em>The total running time of our program is equal to the time of the longest running goroutine.</em></strong></p><p>If we examine the outputs in detail, 2 different problems stand out.</p><p><strong>1)</strong> Outputs are different because we don’t know in what order things will be done. So we can not control the transition between different goroutines.</p><p><strong>2)</strong> How do we know which process will take how long? How do we make sure the job is done?</p><p>Because of the above problems, using goroutines alone is not enough.</p><p><strong>I will explain the concepts of wait groups and channels that we need to solve these problems.</strong></p><h3>Wait Groups:</h3><p>Its main use is to make sure that a goroutine has finished its job. Waitgroups have 3 basic functions as Add(), Done(), Wait()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/372a06b455bed7fe7314ab99c4ffbe9a/href">https://medium.com/media/372a06b455bed7fe7314ab99c4ffbe9a/href</a></iframe><h3>Channels:</h3><p>Channels are a structure which we can put any type of data and read that data simultaneously. So why do we use it? <strong>We use it to move data between 2 different goroutines</strong>. At the same time, <strong>channels also guarantees that the value sent by one routine to another routine available before it is used</strong>.</p><p>For example, we are not allowed to put a return keyword in a goroutine function. We can never bind the program’s progress to the main goroutine to a value from another goroutine. Because we get an error due to the possibility of using it without a return value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6457892c046ee86422bef161f6585fd9/href">https://medium.com/media/6457892c046ee86422bef161f6585fd9/href</a></iframe><p><strong>That’s why we use channels. We channel the value and read that value in the other goroutine.</strong></p><pre>//to write a value into channel</pre><pre>channel &lt;- value</pre><pre>//to read a value from the channel</pre><pre>value &lt;- channel</pre><p>Example usage</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bf46db0341d2e53d07fdb4686ed5122/href">https://medium.com/media/3bf46db0341d2e53d07fdb4686ed5122/href</a></iframe><p>Its important to note that, you can only read the value in a channel which is written by other goroutines. So you can not do both write and read in one channel at the same time. Because channel uses a lock mechanism.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bddaf9c65b6501d00c7d062c61e47a3/href">https://medium.com/media/4bddaf9c65b6501d00c7d062c61e47a3/href</a></iframe><p>I actually have a lot to tell about this subject, but I think it’s been a long enough article. Thank you for giving a time. I hope I was helpful. See you in next article :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a4edb2552b1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/concurrent-programming-with-golang-2a4edb2552b1">Concurrent Programming In Golang</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>