<?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 Abdulbaki Suraj on Medium]]></title>
        <description><![CDATA[Stories by Abdulbaki Suraj on Medium]]></description>
        <link>https://medium.com/@abdulbakisuraj?source=rss-afca7482c03a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T91giJiOjvul-Pf0hjYZMQ.png</url>
            <title>Stories by Abdulbaki Suraj on Medium</title>
            <link>https://medium.com/@abdulbakisuraj?source=rss-afca7482c03a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:57:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdulbakisuraj/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[Hands-On AWS Project: EC2 + ALB vs S3 Static Website Hosting]]></title>
            <link>https://abdulbakisuraj.medium.com/hands-on-aws-project-ec2-alb-vs-s3-static-website-hosting-07233873c0f3?source=rss-afca7482c03a------2</link>
            <guid isPermaLink="false">https://medium.com/p/07233873c0f3</guid>
            <dc:creator><![CDATA[Abdulbaki Suraj]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 22:09:19 GMT</pubDate>
            <atom:updated>2025-10-02T22:13:40.939Z</atom:updated>
            <content:encoded><![CDATA[<p>Cloud computing has changed the way we build and host applications. Some of the ways you can achieve this on AWS is by either running your application on a compute-based service like EC2 or serve files directly form storage-based services like S3.</p><p>In this project, I’ll walk you through deploying a simple HTML page using the two approaches:</p><ol><li>Compute-based hosting with EC2 instances behind an Application Load Balancer (ALB). Here, we’ll be making use of Ansible automation to install and configure Nginx, and deploy our website across multiple instances (servers).</li><li>Storage-based hosting with S3 static webseite hosting</li></ol><p>By the end, you’ll not only have deployed your first AWS project but also understand the key differences between compute and storage hosting and also why one might be better than the other depending on your use case.</p><h3>Prerequisites</h3><p>To follow along, you only need:</p><ul><li>An AWS account</li><li>Ansible installed on your local machine to automate</li><li>Any code editor of your choice</li><li>SSH key pair for connecting to your EC2 instances (you’ll download this when creating the instances)</li></ul><p>We’ll use Ansible for the compute-based deployment (EC2 + ALB), so you’ll see how automation simplifies installing Nginx and deploying the same page across multiple servers.</p><h3>Step 1: Launch 2 EC2 instances</h3><p>We’ll start by creating two Ubuntu EC2 instances on AWS.</p><p>For the purpose of this project, I’ll be making use of the following setup:</p><ul><li><strong>AMI</strong>: Ubuntu 24.04</li><li><strong>Instance type</strong>: t2.micro</li><li><strong>Security group</strong>: allow inbound SSH (port 22) and HTTP (port 80)</li></ul><p>From your AWS console, navigate to the EC2 dashboard.</p><p>This can be done by clicking on the services menu, selecting <strong>Compute</strong> and then <strong>EC2</strong> option from the dropdown menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*EpBmDHvdBj6F_ywKMTrACA.png" /></figure><p>Once you’re in the dashboard, select the ‘<strong>Launch Instance</strong>’ button. This opens up a wizard to setup your <strong>EC2 instance.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*_Zwro7ZXe9Vdy37uP-i24g.png" /></figure><p>Add a unique name for your instance and select the the necessary AMI (Ubuntu) and instance type (t2.micro).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*c6EH4v6TJIqsb3Ao6s0BMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Url3-yDCsbFEeMQMX_1_mQ.png" /></figure><p>Next we create a new SSH key pair. If you already have one, you can select that and skip this part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*JxX8anKx_yTXX3kuiCzsCg.png" /></figure><p>Add a name and then click on the ‘<strong>Create key pair</strong>’ button. This action would automatically select the new key pair and downloaded to your local machine (check your Downloads folder).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*-eoT8O8wZd4O1wTZoPKgIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*1HzdLH776kfyGArDLtwViQ.png" /></figure><p>Next up is the network settings. Click on the ‘<strong>Edit</strong>’ button, so we can update some extra attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*HPm3i3TviFP7nx5HKcvrlA.png" /></figure><p>Leave the other attributes as they are and select the ‘<strong>Availability Zone</strong>’ dropdown. Select any option from the dropdown and note it down. We would need this later when setting up our load-balancer.</p><p>Here, I’ll be choosing ‘us-east-1a’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*sO5iFaPvtTQL_9rnCuj68w.png" /></figure><p>Still in the ‘<strong>Network settings</strong>’, for the <strong>Firewall (security groups)</strong> section, select the ‘<strong>Create security group</strong>’ option. This allows us to setup inbound rules for SSH and HTTP access.</p><p>Set a suitable <strong>‘Security group name</strong>’ and ‘<strong>Description</strong>’.</p><p>For the ‘<strong>Inbound Security Group Rules’</strong>, add ‘ssh’ and ‘HTTP’ from anywhere as seen in the description below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*TUpYiFECSE-N91RBPMvxUw.png" /></figure><p>Finally, at the ‘<strong>Summary</strong>’, click on ‘<strong>Launch instance</strong>’ to start the instance creation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*eKlPHfQdO_4ITbUZkCV8fw.png" /></figure><p>Once the process is finished, click on this link to open up your new EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*vZWxVe6pef27iciD-9w-8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*3LM-d_BIIjCm4TrX6MAH3g.png" /></figure><p>That wasn’t quite hard, was it?</p><p>Now repeat the same step for the second instance with only these two tweaks:</p><ul><li>In the ‘<strong>Key pair</strong>’ section, no need to create another one. You can make use of the one created while setting up the first instance. It can also be used for any subsequent EC2 instances you create.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*1ki1myXnALF2v2NoNsS1Mg.png" /></figure><ul><li>For the ‘<strong>Network settings’</strong>, click the ‘Edit’ button again in order to select any ‘<strong>Availability Zone’</strong> of your choice. Here, I’ll be choosing ‘us-east-1b’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*9SiC15TRBsyXahSja6y15Q.png" /></figure><ul><li>For the ‘<strong>Firewall (security groups)</strong>’, rather than create a new one as well, we can pick the one we creating previously by selecting the ‘<strong>Select existing security group</strong>’ option and then pick the security group we created previously.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*u0jqtVs0UdW0s50xCwnwjQ.png" /></figure><p>Finally, just like the first EC2 instance, in the ‘<strong>Summary</strong>’ section, click on the ‘<strong>Launch instance</strong>’ button to create the second instance.</p><p>Take note of the Public IPv4 addresses of both instances, we would be needing that in the next step.</p><h3>Step 2: Deploy the HTML page on EC2</h3><p>At this point, you have the two EC2 instances running but visiting it via its public IPv4 address (like this http://&lt;ipv4-address&gt;) will throw an error. This is because we haven’t setup any http webserver inside it to serve our files. For this project, we’ll be making use of <a href="https://nginx.org/">Nginx</a>.</p><p>To install Nginx, we can either do it manually by ssh-ing into each instance, manually installing and configuring Nginx or automate it using ansible.</p><p>Before proceeding with any of the options below, in order to avoid an error as seen in the screenshot below preventing you from ssh-ing into the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*5WwYF9TjaRW_pqPK1UUsAA.png" /></figure><p>Run the following command on your private ssh key:</p><pre>chmod 400 /path/to/key-pair.pem</pre><p>This is because OpenSSH refuses to use a private key if the file is too open (e.g., if others can read or write it).</p><h4><strong>Option A: Manual Deployment</strong></h4><ol><li>SSH into each EC2 instance</li></ol><pre>ssh -i /path/to/key-pair.pem ubuntu@public_ipv4_address</pre><p>2. Install Nginx manually</p><pre>sudo apt update &amp;&amp; sudo apt install -y nginx</pre><p>3. Copy your HTML file int the Nginx web root</p><pre>echo &quot;&lt;h1&gt;Hello from this server&lt;/h1&gt;&quot; | sudo tee /var/www/html/index.html</pre><p>4. Start and enable Nginx</p><pre>sudo systemctl enable nginx<br>sudo systemctl start nginx</pre><p>If done correctly, you should see an output like this on your browser when you visit ‘<strong>http://&lt;public_ipv4_address&gt;</strong>’.</p><p>Note that I used ‘<strong>http</strong>’ and not ‘<strong>https</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*0TnGS4BoWWI8FVFf5oFojw.png" /></figure><h4>Option B: Automated Deployment with Ansible</h4><p>If you want to avoid repeating the same steps across multiple servers, then this option is for you.</p><p>Ensure <a href="https://docs.ansible.com/"><strong>Ansible</strong></a> is already installed and running on your local machine.</p><p>In any directory of your choice, we’ll be creating the following files:</p><ol><li><strong>Inventory file (hosts.ini)</strong>: public_ip_1 and public_ip_2 are the public ipv4 address of the first and second instances respectively.</li></ol><pre>[instances]<br>public_ip_1 ansible_user=ubuntu ansible_ssh_private_key_file=/path/to/key-pair.pem<br>public_ip_2 ansible_user=ubuntu ansible_ssh_private_key_file=/path/to/key-pair.pem<br><br>[instances:vars]<br>ansible_ssh_common_args=&#39;-o StrictHostKeyChecking=no&#39;</pre><p><strong>⚠️ Security Note:</strong> Disabling host key checking is fine for labs/tests/cloud instances you rebuild often. In production, it’s better to trust the fingerprint once (ssh-keyscan or manual accept by ssh-ing in manually first) instead of disabling it.</p><p>To confirm we can successfully ssh into the instances, run the command below:</p><pre>ansible instances -i hosts.ini -m ping</pre><p>We should get a success message like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*HFWSi35Lrwxo4oMhwBrT2g.png" /></figure><ul><li><strong>Playbook file (setup.yml)</strong>:</li></ul><pre>---<br>- name: Setup Nginx on EC2 instances<br>  hosts: instances<br>  become: yes<br>  tasks:<br>    - name: Install Nginx<br>      ansible.builtin.apt:<br>        name: nginx<br>        state: present<br>        update_cache: yes<br><br>    - name: Update index.html file<br>      ansible.builtin.copy:<br>        content: &quot;&lt;h1&gt;Hello from {{ inventory_hostname }}&lt;/h1&gt;&quot;<br>        dest: /var/www/html/index.html<br>        owner: www-data<br>        group: www-data<br>        mode: &#39;0644&#39;<br><br>    - name: Start and Enable Nginx<br>      ansible.builtin.service:<br>        name: nginx<br>        state: started<br>        enabled: true</pre><p>Now, run the playbook with:</p><pre>ansible-playbook -i hosts.ini setup.yml</pre><p>Your output should look similar to this. Changed/ok statuses signifies it ran successfully without errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*eLKiL-i_PhjeRUJhcf1uAg.png" /></figure><p>Now when you visit each instances public_ipv4_addresses, you should get something similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*IPvMuj-PcbQXsNUZXDBpJQ.png" /></figure><h3>Step 3: Setup an Application Load Balancer (ALB)</h3><p>Instead of hitting each server separately, we’ll place an ALB in front of them.</p><p>To do that, navigate to <strong>EC2</strong> -&gt; <strong>Load Balancers</strong> -&gt; <strong>Create Load Balancer</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*vdKuGPvJukCSqDbVSwuqfA.png" /></figure><p>Select ‘<strong>Application Load Balancer</strong>’ and then click ‘<strong>Create</strong>’ button to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*DjugMzxXvDKFtu9FAyMQZA.png" /></figure><p>In the ‘<strong>Basic configuration</strong>’ section, set a unique ‘<strong>Load balancer name</strong>’ , select ‘<strong>Internet-facing</strong>’ option as the Scheme and then ‘<strong>IPv4</strong>’ option for IP address type as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*3HhEhBASxfYgI7mi6e8Isg.png" /></figure><p>In the ‘Network mapping’ section, select the whatever ‘<strong>Availability Zones and subnets</strong>’ that was selected previously when setting up each instances earlier on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*YFilyDt1vic5XVQQG9FsFQ.png" /></figure><p>Same thing for the ‘<strong>Security groups’.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*0yZNRVHNJpApDbhYWPUmJw.png" /></figure><p>For the listeners, ensure the ‘HTTP’ protocol and port ‘80’ is used.</p><p>Select ‘<strong>Forward to target groups</strong>’ for the ‘<strong>Routing action’ </strong>and then click on the ‘<strong>create target group</strong>’. This might open up a new page in a different tab so bare this mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*XFttWElxmRB99To7Bxm3jg.png" /></figure><p>On the ‘Create target group’ page, select the options as described below:</p><ul><li><strong>Target type</strong>: instances</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*5xXb8qx1reNGCsOwIWlljQ.png" /></figure><ul><li><strong>Target group name:</strong> any unique name</li><li><strong>Protocol and port</strong>: HTTP and 80</li><li><strong>IP address type</strong>: IPv4</li><li><strong>Protocol version</strong>: HTTP1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*9UcXVoBN51Vt5L-PhCdCDw.png" /></figure><p>Click on ‘<strong>next</strong>’ button and on the next page, select the two instances we created previously and then click ‘<strong>Include as pending below</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*14GWr2tuYSplA9DDMSY0Ng.png" /></figure><p>Finally, click <strong>‘Create target group</strong>’ to create the target group with the selected instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*jHYXJIv8b8I8d1288KNrZg.png" /></figure><p>You should see this once the process has finished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*MGujy6ki2LSEAZ6Vr9SmIw.png" /></figure><p>Now go back to the previous page/tab (where we were setting up the load balancer), and click the refresh button just beside the ‘<strong>Target group</strong>’ select field.</p><p>You should now see the newly created target group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*NMCQE3wfCuGoADaBu2bQWA.png" /></figure><p>Now, after reviewing everything and making sure its correct, click on ‘Create load balancer’ to start the creation process.</p><p>This would take a while to provision but your page should look something like this. You’ll know its ready once the ‘<strong>Status</strong>’ goes from ‘Provisioning’ to ‘Active’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*pTVNIcGrHRvhkJucKNv3GQ.png" /></figure><p>Copy the ‘<strong>DNS name</strong>’ and then visit it in your browser. In this case, that should be something like ‘http://ec2-alb-435792316.us-east-1.elb.amazonaws.com’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*oCyDmHq33L26GkuWwh67rg.png" /></figure><p>Awesome, now we have a working load balancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*PmQDQ_0GJiRYfXSNvrSD9g.png" /></figure><p>Refresh the page enough times and you should hit the other instance as well .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*TSq26el4_GupqKVMBr-CKg.png" /></figure><h3>Step 4: Deploy an HTML file to S3</h3><p>From the console navigate to <strong>Storage </strong>-&gt; <strong>S3 </strong>and then click ‘<strong>Create Bucket</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*5rHpVwyysNI1lhtFPeetew.png" /></figure><p>Set a globally unique <strong>Bucket name </strong>and disable <strong>Block Public Access settings for this bucket </strong>as shown below and click <strong>Create bucket </strong>at the bottom of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ZvcxH8PTK3KsbZj-sABUsA.png" /></figure><p>Once its created, click <strong>View details </strong>to open the bucket page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*tDCyIEnhcH6aMOXI6WRs8g.png" /></figure><p>Click on <strong>Upload </strong>to add your index.html (and other necessary files) to the bucket.</p><p><em>Link to the index.html file I uploaded — </em><a href="https://github.com/codelikesuraj/alb-ec2-s3-tutorial"><em>https://github.com/codelikesuraj/alb-ec2-s3-tutorial</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*D-XvGxHz6bPkABexNDko1w.png" /></figure><p>After successfully upload your file(s), go to the <strong>Properties</strong> section and scroll to <strong>Static website hosting</strong> and then click on<strong> Edit.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ruun-7N5iUcmZ2ovExaMEw.png" /></figure><p>Enable it and select ‘Host a static website’ for the <strong>Hosting type </strong>and then<strong> Save changes.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*2J3r3ke9-Rs_btNNys3Wzg.png" /></figure><p>Now, AWS will give you a <strong>Bucket website endpoint</strong> like this <strong>http://s3-oct-2025.s3-website-us-east-1.amazonaws.com.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*bHqIYiGQmnNMvAI3XDJ2-A.png" /></figure><p>If you attempted to visit that directly, you would be getting an error like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*SiUSPWVEOudL_u3MoeYukA.png" /></figure><p>This is because by default, S3 objects are private. We need to allow public read access.</p><p>Now, go the <strong>Permissions</strong> tab and click <strong>Edit</strong> in the <strong>Bucket policy </strong>section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*UfdZEps7mTWIR6EEgqF7WQ.png" /></figure><p>Paste this into the <strong>Policy</strong> field and then <strong>Save changes.</strong></p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: &quot;*&quot;,<br>      &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::s3-oct-2025/*&quot;<br>    }<br>  ]<br>}</pre><p>Note: replace the ‘arn:aws:s3:::s3-oct-2025’ with your <strong>Bucket ARN</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*WEK4uPWwygRwlJ4TG23LJw.png" /></figure><p>Revisit the <strong>Bucket website endpoint </strong>and your website should be accessible now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*SEYTf2jvCiWGDPiv1pd0Yg.png" /></figure><h3>Conclusion</h3><p>This hands-on projected demonstrated two fundament hosting setup on AWS:</p><ul><li>With EC2 + ALB, you get full control of the server environment, making it ideal for dynamic applications and backends. However, this comes with management overhead and costs since you’re running compute resources.</li><li>With S3 static website hosting, you get a lightweight, cost-effective, and infinitely scalable way to serve static sites. Perfect for documentation, portfolios, or frontend projects that don’t need server-side logic.</li></ul><p>Both approaches serve different purposes. The real skill lies in knowing when to choose one over the other.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07233873c0f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Server-Sent Events in Go: A Practical Guide]]></title>
            <link>https://abdulbakisuraj.medium.com/implementing-server-sent-events-in-go-a-practical-guide-87fdb3024fd7?source=rss-afca7482c03a------2</link>
            <guid isPermaLink="false">https://medium.com/p/87fdb3024fd7</guid>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Abdulbaki Suraj]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 09:29:35 GMT</pubDate>
            <atom:updated>2025-07-03T10:46:24.719Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever been on a website where data, text, or graphs automatically update without you needing to refresh the page? Think of stock charts, timers, real-time chats, or in-browser notifications that pop up as you browse. These dynamic updates are often powered by Server-Sent Events (SSE) working seamlessly in the background. In this guide, I will be showing you how to easily implement in Go.</p><h3>What are Server-Sent Events?</h3><p>Server-Sent Events (SSE) are a type of web technology that allows a client to automatically recieve and subscribe to updates from the server via an open HTTP connection. This type of connection is uni-directional in the sense that data flows in only one direction — from the server to the client.</p><figure><img alt="Illustration showing the direction of data from server to client" src="https://cdn-images-1.medium.com/max/662/1*C44ED_HzNKe74RVMS6BU-g.png" /><figcaption>Server sending data to client.</figcaption></figure><h3>How does it work?</h3><p>The client (in this case our browser) initiates an HTTP request to the server requesting to subscribe to an event. This is achieved by calling the <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource">EventSource</a> web API which comes with some default header parameters like “Accept: text/event-stream” parameter.</p><p>The server on the other hand then accepts this connection request with a “Content-Type: text/event-stream” response keeping the connection open and subsequently, sends updates via the newly created connection to the client.</p><figure><img alt="Illustration depicting request-response timeline between the client and the server" src="https://cdn-images-1.medium.com/max/761/1*gGb59b_jc8w9_JdlXc0VPg.png" /><figcaption>Request-response timeline between the client and server</figcaption></figure><p>Updates in SSEs are represented in text-based format with a compulsory “data: ” text at the beginning, followed by an whatever message you want to send from the server and ending with <strong>two</strong> newline characters “\n\n”. This structure represents a single update sent over the connection.</p><p>Here’s what that might look like if we were to send “Hello World” in across such connection:</p><pre>Example 1:<br>  data: Hello world in a single line\n\n<br><br>Example 2:<br>  data: Hello world\n<br>  data: in two\n<br>  data: or more lines\n\n</pre><h3>Let’s write some code</h3><p>For this purpose of this guide, we are going to be making a simple random web quotes display. This will be streamed directly from our server and updated at interval in our browser.</p><p>To get started, setup up a new Go project and open it up in any code editor of your choice.</p><figure><img alt="A screenshot of setting up a Go project in a new folder." src="https://cdn-images-1.medium.com/max/765/1*sDdJMmUjdTTn9N95OIfbtA.png" /><figcaption>Setting up a Go project in a new folder</figcaption></figure><p>Create a new “index.html” file in the root directory and copy and paste the code below into it. This is just a blank html template we’ll be using to display the quotes.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Random Quote Generator&lt;/title&gt;<br>    &lt;style&gt;<br>      body {<br>        box-sizing: border-box;<br>        margin: 0;<br>        display: flex;<br>        align-items: center;<br>        justify-content: center;<br>        min-height: 100vh;<br>      }<br>      .quote {<br>        margin: auto;<br>        width: 75%;<br>        font-size: xx-large;<br>        text-align: center;<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div class=&quot;quote&quot;&gt;Random quote - Author&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>And now create a “main.go” file in that same directory and copy the code below into it.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;net/http&quot;<br>)<br><br>const PORT = &quot;8080&quot;<br><br>func main() {<br> http.Handle(&quot;/&quot;, http.FileServer(http.Dir(&quot;.&quot;)))<br><br> err := http.ListenAndServe(&quot;:&quot;+PORT, nil)<br> if err != nil {<br>  log.Fatal(&quot;error starting server on port &quot; + PORT)<br> }<br>}</pre><p>Finally, in the root directory, run the command go run main.go and if everything is setup properly, you should have something similar to this.</p><figure><img alt="Screenshot showing a text centered in our browser tab screen." src="https://cdn-images-1.medium.com/max/700/1*VYeDxDrJufZb1jKnKmkp-w.png" /><figcaption>“A random quote — Author” at the center of the screen</figcaption></figure><p>Next up, we are going to be updating our “main.go” file to manage the endpoint for the events.</p><p>Create a global “quotes” variable to store our quotes.</p><pre>var quotes = []string{<br> &quot;The web is more a social creation than a technical one. I designed it for a social effect—to help people work together. — Tim Berners-Lee&quot;,<br> &quot;Content precedes design. Design in the absence of content is not design, it’s decoration. — Jeffrey Zeldman&quot;,<br> &quot;The best websites are ones that give the users what they want, while at the same time meeting the needs of the business. — Steve Krug&quot;,<br> &quot;A website without visitors is like a ship lost in the horizon. — Dr. Christopher Dayagdag&quot;,<br> &quot;Websites should look good from the inside and out. — Paul Cookson&quot;,<br> &quot;Web design is not just about creating pretty layouts. It’s about understanding the marketing challenge behind your business. — Mohamed Saad&quot;,<br> &quot;The web is like a dominatrix. Everywhere I turn, I see little buttons ordering me to submit. — Nytwind&quot;,<br> &quot;Your website is the center of your digital ecosystem. Like a brick-and-mortar location, the experience matters once a customer enters. — Leland Dieno&quot;,<br> &quot;The great thing about web design is that you can do it on your own. All you need is a computer, an internet connection, and a lot of determination. — Mike Sullivan&quot;,<br> &quot;The key to making great websites is to not make them feel like websites. — Nick Disabato&quot;,<br>}</pre><p>Next create an “eventsHandler” function to handle the event stream request.</p><pre>func eventsHandler(w http.ResponseWriter, r *http.Request) {<br> w.Header().Set(&quot;Content-Type&quot;, &quot;text/event-stream&quot;)<br><br> for _, quote := range quotes {<br>  fmt.Fprintf(w, &quot;data: %s\n\n&quot;, quote)<br>  w.(http.Flusher).Flush()<br>  time.Sleep(5 * time.Second)<br> }<br>}</pre><p>Here, we can see that the following things are happening:</p><ol><li>The handler initially sets the “Content-Type” of the response to “text/event-stream”.</li><li>We then iterate over the list of quotes, each time sending the quotes to the client as a single event</li><li>fmt.Fprintf(w: “data: %s\n\n”, quote) sends the quote to the client. The “data:” prefix is part of the SSE protocol and “\n\n” indicates the end of the event.</li><li>w.(http.Flusher).Flush() sends the data to the client without waiting for the response to complete.</li><li>time.Sleep(5 * time.Second) introduces a 5-second delay between sending each quote.</li></ol><p>Finally, we can add an endpoint to accept the event stream requests.</p><pre>...<br>http.HandleFunc(&quot;/quotes&quot;, eventsHandler)<br>...</pre><p>The final main.go file should look something like this:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net/http&quot;<br> &quot;time&quot;<br>)<br><br>const PORT = &quot;8080&quot;<br><br>var quotes = []string{<br> &quot;The web is more a social creation than a technical one. I designed it for a social effect—to help people work together. — Tim Berners-Lee&quot;,<br> &quot;Content precedes design. Design in the absence of content is not design, it’s decoration. — Jeffrey Zeldman&quot;,<br> &quot;The best websites are ones that give the users what they want, while at the same time meeting the needs of the business. — Steve Krug&quot;,<br> &quot;A website without visitors is like a ship lost in the horizon. — Dr. Christopher Dayagdag&quot;,<br> &quot;Websites should look good from the inside and out. — Paul Cookson&quot;,<br> &quot;Web design is not just about creating pretty layouts. It’s about understanding the marketing challenge behind your business. — Mohamed Saad&quot;,<br> &quot;The web is like a dominatrix. Everywhere I turn, I see little buttons ordering me to submit. — Nytwind&quot;,<br> &quot;Your website is the center of your digital ecosystem. Like a brick-and-mortar location, the experience matters once a customer enters. — Leland Dieno&quot;,<br> &quot;The great thing about web design is that you can do it on your own. All you need is a computer, an internet connection, and a lot of determination. — Mike Sullivan&quot;,<br> &quot;The key to making great websites is to not make them feel like websites. — Nick Disabato&quot;,<br>}<br><br>func main() {<br> http.Handle(&quot;/&quot;, http.FileServer(http.Dir(&quot;.&quot;)))<br> http.HandleFunc(&quot;/quotes&quot;, eventsHandler)<br><br> log.Println(&quot;Server listening on http://localhost:&quot; + PORT)<br> err := http.ListenAndServe(&quot;:&quot;+PORT, nil)<br> if err != nil {<br>  log.Fatal(&quot;error starting server on port &quot; + PORT)<br> }<br>}<br><br>func eventsHandler(w http.ResponseWriter, r *http.Request) {<br> w.Header().Set(&quot;Content-Type&quot;, &quot;event-stream&quot;)<br><br> for _, quote := range quotes {<br>  fmt.Fprintf(w, &quot;data: %s\n\n&quot;, quote)<br>  log.Println(&quot;Sent &#39;&quot; + quote + &quot;&#39; to the client&quot;)<br>  w.(http.Flusher).Flush()<br>  time.Sleep(5 * time.Second)<br> }<br>}</pre><p>Now that we have our server setup, next up a little bit of Javascript in our index.html file to subscribe to the updates.</p><p>Inside your body tag, just below the &lt;div class=”quote”&gt;Random quote — By Author&lt;/div&gt;, add the following Javascript:</p><pre>&lt;script text=&quot;type/javascript&quot; defer&gt;<br>  const eventSource = new EventSource(&quot;/quotes&quot;);<br>  const quoteBox = document.querySelector(&quot;.quote&quot;);<br><br>  eventSource.addEventListener(&quot;message&quot;, function (event) {<br>    quoteBox.textContent = event.data;<br>  })<br>&lt;/script&gt;</pre><p>Another breakdown on what’s happening in the JS script.</p><ol><li>The <a href="https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events">EventSource</a> object connects to the server at the endpoint “/quotes” which provides the SSE stream.</li><li>We then select the HTML quote element const quoteBox = document.querySelector(“.quote”); and assign it the quoteBox variable. This is where the quotes will be displayed.</li><li>An event listener is then set up to listen for ‘message’ events from the stream. This is the default event set in any SSE stream. The ‘event’ object in the callback function contains the data sent from the server, in our case ‘event.data’.</li><li>The textContent of the quoteBox is then updated with the data received from the server. This means that everytime we receive data from the server, the content in the quoteBox is replaced with the new quote.</li></ol><p>Our final index.html file should look something like this now.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Random Quote Generator&lt;/title&gt;<br>    &lt;style&gt;<br>      body {<br>        box-sizing: border-box;<br>        margin: 0;<br>        display: flex;<br>        align-items: center;<br>        justify-content: center;<br>        min-height: 100vh;<br>      }<br>      .quote {<br>        margin: auto;<br>        width: 75%;<br>        font-size: xx-large;<br>        text-align: center;<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div class=&quot;quote&quot;&gt;A random quote - Author&lt;/div&gt;<br>    &lt;script text=&quot;type/javascript&quot; defer&gt;<br>      const eventSource = new EventSource(&quot;/quotes&quot;);<br>      const quoteBox = document.querySelector(&quot;.quote&quot;);<br><br>      eventSource.addEventListener(&quot;message&quot;, function (event) {<br>        quoteBox.textContent = event.data;<br>      });<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Try running the go run main.go command again now and watch your website come to life.</p><figure><img alt="Animated gif of random quotes displaying at intervals on a browser tab." src="https://cdn-images-1.medium.com/max/600/1*zUuFBlugy-7RmC6ro12oVQ.gif" /><figcaption>Animated gif of random quotes displaying at intervals on a browser tab.</figcaption></figure><h3>Conclusion</h3><p>Integrating Server-Sent Events into your Go applications unlocks to door to providing real-time and dynamic user experiences without the need for constant client-side requests.</p><p>This guide only offers an implementation in its most basic form as considering other factors like security, performance, and customizations will definitely go beyond the scope stated.</p><p>So take your time, experiment, break stuffs, fix them, break them again and continue through that vicious but rewarding cycle. Experience will always be the best way to learn.</p><p>You can find link to the source code used here in my github repository and also a live link below:</p><ul><li><strong>Github repo</strong>: <a href="https://github.com/codelikesuraj/sse-tutorial">http://github.com/codelikesuraj/sse-tutorial</a></li><li><strong>Live demo</strong>: <a href="https://sse-tutorial.abdulbakisuraj.com/">https://sse-tutorial.abdulbakisuraj.com</a></li></ul><p>Have fun 👋</p><h3>Some helpful resources</h3><ul><li><a href="https://html.spec.whatwg.org/multipage/server-sent-events.html">https://html.spec.whatwg.org/multipage/server-sent-events.html</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource">https://developer.mozilla.org/en-US/docs/Web/API/EventSource</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87fdb3024fd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving a Backend Challenge: My Journey with Golang and Hexagonal Architecture]]></title>
            <link>https://abdulbakisuraj.medium.com/solving-a-backend-challenge-my-journey-with-golang-and-hexagonal-architecture-102743a5ed96?source=rss-afca7482c03a------2</link>
            <guid isPermaLink="false">https://medium.com/p/102743a5ed96</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Abdulbaki Suraj]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 17:19:41 GMT</pubDate>
            <atom:updated>2024-08-28T06:25:25.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OSHmKCoabdC5nQ4g" /><figcaption>Photo by <a href="https://unsplash.com/@jasonstrull?utm_source=medium&amp;utm_medium=referral">Jason Strull</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Picking up a new language in my journey as a backend developer has been nothing short of exciting and challenging. My latest project, a CLI application written in Golang (also called Go) interfacing with a fintech API, tested my skills in ways I hadn’t anticipated. As someone with a background in PHP and a newfound passion for Golang, this project was a significant step in my career.</p><h4>The Problem: Integrating a Fintech API with Hexagonal Architecture</h4><p>I decided to build a CLI application using Go that would interface with Paystack’s payment request endpoints. My goal was to create a tool that allowed users to manage requests for payment of goods and services. The challenge was not just in the integration but in designing the application using hexagonal architecture — a pattern that emphasizes the separation of concerns, making the code more maintainable and testable.</p><h4>The Solution</h4><p>To fully achieve the end goal of this project, I decided to break down the project into actional steps that would make it attainable which I will be describing below.</p><h4><strong>Step 1: Understanding hexagonal architecture</strong></h4><p>I started by researching and understanding the key principles of hexagonal architecture. This foundation was crucial as it guided the structuring of my code.</p><p>Hexagonal architecture, also known as ports and adapters aims to create loosely coupled application components that are easy to maintain and test. This architecture which divides the application into distinct parts — <strong>the domain </strong>which contains the core logic that makes the application work, <strong>the ports </strong>which act as the interfaces that define what actions the core logic can perform, and <strong>the adapters </strong>which handles communication with the other external components (e.g databases and other web services).</p><h4>Step 2: Setting up the project</h4><p>Considering this project was going to be a command-based project, I didn’t want to worry too much on parsing arguments, flags and so on but rather focus on the core logic, I decided to use spf13’s Cobra-cli, a library for creating powerful CLI applications in Go. With this, I was able to define commands and their respective flags easily.</p><h4>Step 3: Implementing the core logic</h4><p>The core logic of the application was centered around creating, listing, and fetching payment requests. I defined these operations in the “cmd” folder created by the cobra cli.</p><p>Adapters were created to handle the actual communication with Paystack’s API. These included HTTP clients that made requests to the endpoints and parsed the responses.</p><p>By keeping these adapters separate, I ensured that any changes to the API or the way requests were made wouldn’t affect the core logic.</p><p>Flags and parameters were added to these commands to provide flexibility to the users.</p><h4>Step 4: Testing and debugging</h4><p>Testing was an integral part of the development process. I wrote end-to-end tests to verify the entire flow, from command invocation to API interaction.</p><h4>The Journey with HNG Internship</h4><p>Embarking on this project was a way to challenge myself and grow as a backend developer. The HNG Internship is an incredible opportunity to further this growth. By working on real-world projects within constrained deadlines and collaborating with other talented developers, I aim to get the best out of the program and improve my skills while contributing meaningfully to the tech community.</p><p>The HNG Internship offers a platform to learn, innovate, and excel. Whether you’re a newbie or an experienced developer, the program is designed to push your limits and help you achieve your goals. If you’re passionate about tech and looking for a transformative experience, I highly recommend checking out the <a href="https://hng.tech/internship">HNG Internship</a> and <a href="https://hng.tech/hire">HNG Hire</a> websites.</p><h4>Conclusion</h4><p>Solving complex backend problems requires a mix of technical knowledge, creativity, and perseverance. This project not only enhanced my understanding of Go and hexagonal architecture but also prepared me for the challenges and opportunities that lie ahead with the HNG Internship. I am excited about this journey and look forward to the experiences and learning it will bring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102743a5ed96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send PHP errors to Telegram with lograh-php package]]></title>
            <link>https://abdulbakisuraj.medium.com/send-php-errors-to-telegram-with-lograh-php-package-2c864f25cc52?source=rss-afca7482c03a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c864f25cc52</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[telegram]]></category>
            <dc:creator><![CDATA[Abdulbaki Suraj]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 13:20:24 GMT</pubDate>
            <atom:updated>2024-03-20T13:20:24.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R2TMiZMTeFhfRgT_" /><figcaption>Photo by <a href="https://unsplash.com/@kobuagency?utm_source=medium&amp;utm_medium=referral">KOBU Agency</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><h4>Error handling in PHP</h4><p>Error handling is one of the critical aspects of any PHP application. When unexpected situations occur during program execution, proper error management ensures that the application can easily handle these scenarios without crashing or producing undesirable outcomes.</p><p>In PHP, the ‘try’ and ‘catch’ constructs are fundamental components of the language’s exception handling mechanism. These basically tells the source code to ‘try’ and execute a block of code and if an exception occurs, it ‘catch’es it and any action can be taken in the ‘catch’ block without stopping the running process.</p><p>Here’s a basic example of a try-catch block in action.</p><pre>&lt;?php<br> try {<br>  // run piece of code that may throw an exception<br> } catch (\Throwable $exception) {<br>  // log or process the exception<br>  echo “Caught an exception: “ . $exception-&gt;getMessage();<br> }<br> // do some other things</pre><p>In this example, we have a ‘try’ block that might throw an exception and if one were to occur, it is caught in the corresponding ‘catch’ block and you can access any information about the exception from the ‘$exception’ variable.</p><h4>The lograh-php package</h4><p>Let’s say we have a scenario where you have a critical process running in your PHP project and you would like to be notified outside of your app as soon as an exception occurs. There are a lot of packages and third-party tools out there that can be used to implement, but a host of them are either too complicated to set up, have a lot of dependencies (which can impact performance) or cost you to use.</p><p>The lograh-php package is a very light-weight solution for this as it easily utilizes Telegram’s popular Bots API, allowing you to send information about these exceptions directly to any dedicated chat, group or channel on your Telegram account.</p><h3>Setup</h3><p>Before you can use this package, you need a Telegram Bot setup on your account. What we need here is the API Key generated after creating your Bot and your chat, group or channel ID.</p><h4>Obtain your bot token</h4><p>Obtaining your Bot token is a pretty straightforward process in the steps listed below.</p><p>Follow this link <a href="https://t.me/botfather">https://t.me/botfather</a> to interact with the BotFather to generate a new Telegram bot.</p><p>Once it opens up, if not already selected, type in the command ‘/newbot’ in the message box or select the option from the side menu and follow through with the prompts as shown in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*6IR3FoIChKx7Ro5D" /></figure><p>Copy the token and keep in a secure place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*SGghY9FSIsq3QbgRrmZrpw.png" /></figure><p>Then click on your bot link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*4OGfWiYVcGddOopeCIX03A.png" /></figure><p>This takes you to a chat window with your window, then you click “Start” button at the bottom of the screen or enter the “/start” command in the message box.</p><h4>Get your chat ID</h4><p>Your chat ID is used to identify the chat that the logs would be sent to. This could be your direct inbox, a public/private that you have admin access to. In this scenario, we will be sending the logs directly to your chat.</p><p>Follow this link <a href="https://t.me/userinfobot">https://t.me/userinfobot</a> to interact with the “userinfobot” to display your user info when you forward a message to it.</p><p>Click the “start” button on the bottom of the screen or type in the command “/start”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*cQIGaQVe7N-9ZE_R" /></figure><p>This should show your user details.</p><p>Copy your ID and also keep in a secure place for later.</p><h4>Include the lograh-php package</h4><p>If your PHP project is setup with composer, you can easily import the package by running the command below</p><pre>composer require codelikesuraj/lograh-php</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*Ert1f_B8VLpkPL2o" /></figure><p>Or you can copy/clone the project from github, <a href="https://github.com/codelikesuraj/lograh-php">https://github.com/codelikesuraj/lograh-php</a>.</p><h3>Usage</h3><p>We are going to be using a skeleton project I created specifically for this tutorial, you can check out the source-code here <a href="https://github.com/codelikesuraj/lograh-tut">https://github.com/codelikesuraj/lograh-tut</a>.</p><p>Create an index.php file in the root of the project</p><pre>touch index.php</pre><p>Inside the index.php file, initialize an instance of the LograhPHP\Logger class with your project name, bot token and chat ID.</p><pre>&lt;?php<br>require_once(&quot;vendor/autoload.php&quot;);<br><br>$logger = new Codelikesuraj\LograhPHP\Logger(<br>    appName: &quot;Lograh Tutorial&quot;,<br>    botToken: &quot;api_key_generated_from_your_telegram_bot&quot;,<br>    chatId: &quot;id_of_your_telegram_chat_or_channel_or_group&quot;<br>);</pre><p>Then add this simple try-catch block just below it.</p><pre>try {<br>    throw new \Exception(&quot;I am an error from Lograh-tut&quot;);<br>} catch (\Throwable $exception) {<br>    // send exception to Telegram using any<br>    // of the following methods<br>    $logger-&gt;reportAsText($exception);<br>}</pre><p>Now run the code and you should receive a message on your telegram that looks something like this.</p><pre>php index.php</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*NHVCafMQsX6Yhdcd" /></figure><p>Also, for a JSON style message, you can use either use the ‘reportAsJson()’ or ‘reportAsJsonWithStackTrace()’ method which as the name suggests sends the report as a JSON without and with the stack trace respectively.</p><p>Here’s a sample of what those implementations might look like.</p><pre>$logger-&gt;reportAsJson($exception);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*nqtinKsplKE8aP8v" /></figure><pre>$logger-&gt;reportAsJsonWithStackTrace($exception);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*oaJn1SYcZ6X-48Pd" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c864f25cc52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started as a backend developer: A beginner’s guide]]></title>
            <link>https://abdulbakisuraj.medium.com/getting-started-as-a-backend-developer-a-beginners-guide-5fac9cd6b500?source=rss-afca7482c03a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fac9cd6b500</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Abdulbaki Suraj]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 19:14:45 GMT</pubDate>
            <atom:updated>2024-03-10T09:47:03.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SJes5yN9FM1DZev-" /></figure><p>Getting started in anything these days is usually hard for beginners than people actually realize. With a huge number of resources on the web and easy accessibility from anywhere in the world, navigating the right path can be an exhausting task.</p><p>In this post, I try to get you acquainted with the backend development space, a guide on what to learn and a few lists of resources to get you started.</p><h3>What is Backend Development?</h3><p>Backend is a term used to describe the unseen activities that happen in the background whenever any action is taken on a website. Those actions could include signing in, creating an account, accessing resources on a web application, purchasing an item in an online store and so on.</p><p>Backend development also sometimes referred to as server-side development involves creating logic and code that interacts with a database or storage media stored on a server, a programming interface that exchanges information between the user on the frontend (the part of the website the user can see and interact with) and the database and then output necessary information back to the user.</p><h3>Who is Backend Developer?</h3><p>Now that we know what backend development is, we can say that a Backend Developer is responsible for managing all activities that occurs on a web server.</p><h3>Roles of a Backend Developer</h3><ul><li>Writing server-side logic with a programming language of choice</li><li>Processing data from user requests and performing actions on them</li><li>Ensuring data is only accessible to users that are supposed to have access to it</li><li>Fixing website bugs and errors</li><li>Creating and managing databases</li><li>Collaborating with the frontend to provide seamless communication between the frontend and backend</li><li>Developing and integrating APIs to connect with other backend applications and services</li></ul><h3>Getting started</h3><p>Before we dive head first into Backend Development, there are a few concepts and underlying architecture we need to understand, most of which forms an integral part of whatever we are going to be discussing and doing in the future.</p><h3>Prerequisite Knowledge</h3><p>Having a basic knowledge of the underlying technology isn’t a waste of time. This usually proves useful in the long run and some of them include but are not limited to the following:</p><ul><li><strong>The Internet</strong>: How it works, what HTTP is, how browsers work, hosting etc.</li><li><strong>Database</strong>: Types (relational vs non-relational) and their use cases.</li><li><strong>Servers</strong></li><li><strong>Frontend</strong>: Have a basic knowledge of front-end technologies and languages like HTML, CSS and JavaScript. Trust me on this, understanding how your data will be displayed to and submitted by the user will help you when formatting input and output. It also helps in understanding the structure of the frontend and how to effectively interact with it.</li></ul><h3>Pick a Backend Language</h3><p>Picking a language to start with is another daunting task but I will suggest starting with one and learning its perks as well as its limitation.</p><p>One good thing about learning a language is that when you decide the current one isn’t cutting it for you, learning another one won’t be hard as the knowledge of programming concepts such as loops, functions, variables etc. of one language is transferrable to other languages with a differences in its syntax and structure.</p><p>There are a few programming languages which are suitable for writing backend code but I will only be listing the commonly used ones in no particular order. These include but are not limited to the following:</p><p>Amongst the above list, I started with and still use PHP as it runs on various platforms (Linux, windows etc.) and its compatible with almost all web servers used today (Apache, IIS). Its free to use and also easy to learn while supporting a wide range of relational databases such as MySQL which is another popular and widely used database.</p><p>After picking a language, learn basic concepts like variables, loops, functions, arrays, if-else and switch statements and then ones you have a grasp of these, take it a step further by learning OOP — Object Oriented Programming if the language supports. This is not a must yet, but you’ll eventually need to learn that.</p><h3>Pick a Database Management Systems</h3><p>You have learned how to write code with your preferred language but you feel like something is missing. All the codes you have been writing up till this point probably won’t have persistent data, that is, the user inputs are stored temporarily. This is where a database comes in. It helps retain such data and provides them again on request for reading and modification.</p><p>A Database Management System (DBMS) is kind of like the software used in managing the database itself. This could further be classified based on the database model they support which can be <strong>Relational databases</strong> (usually made up of a series of tables that contains rows and columns and they use a Structured Query Language (SQL) for interacting with the data) and <strong>Non-relational databases</strong> (also referred to as NoSQL, doesn’t use the tabular form of storage used by relational databases).</p><p>For starters, go with a relational database and my preferred choice would be MySQL as it pairs nicely with my preferred language which is PHP.</p><p>It is not a must for you to go with these choices, your choice of backend language and database may differ from mine, just do a bit more research and find a pair that works for you.</p><h3>Learn basic CRUD operations</h3><p>You must be wondering what CRUD means by now, don’t worry its nothing technical. Its just an acronym for the basic operations that occurs in the backend which are</p><ul><li><strong>C</strong>reate: receive data from frontend and save to the database,</li><li><strong>R</strong>ead: fetch data from the database and output to the frontend,</li><li><strong>U</strong>pdate: edit and update data stored in the database, and</li><li><strong>D</strong>elete: delete data stored in the database.</li></ul><p>There are few tutorials online (videos and articles) detailing how to go about this in your language and database of choice.</p><h3>Learn authentication and authorization</h3><p>After getting comfortable with CRUD operations, how about we put some privacy into it. Up until this point, any user has access to all parts of your web application. In order to prevent this and allow only certain users to have access to certain parts, information and actions on your web application, we need to add authorization logic to your web application.</p><p>This involves creating login and signup code (authentication) which only allows users to have access to other parts of your application asides the login and signup screen and then based on the type of users (whether standard or administrator) you restrict access to some other parts further inside you application.</p><h3>Start building projects</h3><p>If you’ve managed to persevere and get this far in your learning path, I can confidently say that you’re on your way to becoming a world-class backend developer. Since you can confidently write code to create, read, update and delete data from a database, add authentication and authorization to your application, I think you can build the next Facebook now.</p><p>I am only kidding though, but with these you can start with projects from as little as a Todo List (every beginner’s favorite) and then tune it up a bit by adding authentication and authorization in order to allow only the owners to view their own lists.</p><h3>Learn a framework</h3><p>You have been working on a few projects now and have begun to notice some repeating patterns, a typical example being writing login and signup logic, authorization, writing logic to save and retrieve data from the database and they are beginning to get tedious.</p><p>Some of you might have even found libraries and packages online, others may have a reusable and customizable template they created to help with them with these tasks, anyways, you are all trying to make your work easier and focus more on what matters right, and that’s where this wonderful thing called <strong>FRAMEWORKS</strong> come in.</p><p>A framework is a programming tool or set of reusable codes that come with pre-written components or solutions that can be customized in order to speed up development. Using framework can save you huge amount of time that would have been spent building things from the ground up and because of this, reduces the chances of errors.</p><p>Other reasons to use frameworks are:</p><ul><li>reduce code duplication,</li><li>simpler testing and debugging,</li><li>you can focus on writing code that is specific to your project (more like business logic),</li><li>easily reusable,</li><li>comes preinstalled with industry-standard conventions and security measures etc.</li></ul><p>Frameworks are usually built on top of existing programming languages some of which include but are not limited to the following:</p><ul><li>PHP — Laravel, Symfony, CodeIgniter, Yii, CakePHP etc.</li><li>Python — Django, Flask etc.</li><li>NodeJS (JavaScript) — Express.js, Meteor.js etc.</li><li>Ruby — Ruby on Rails, Sinatra, Camping etc.</li><li>Java — Spring etc.</li><li>Golang — Fiber etc.</li></ul><h3>Final notes</h3><p>One simple strategy that has always helped people to grow in this field is to learn by doing. Don’t get caught up watching tutorials, reading blog posts and never actually taking your time to practice all you have learned, take time after learning to apply this by building projects. Most people make a mistake of learning a lot of theory without actually applying it.</p><p>It doesn’t matter if you picked up some dude’s code from the internet, take your time, read it, yes, I know what I said, read the code. Understand the purpose and what every function is trying to achieve then try recreating it by building your own.</p><p>You need not create an exact copy of the project but provided you understood what it was trying to achieve and the process that was taken to achieve then you’re good.</p><p>Take your time, understand concepts and keep on improving on your skills. Join communities and reach out whenever you are having issues and let google be your best friend. Even senior developers still search for a few things once in a while 😊.</p><p>There is still a lot more topics to discuss and expand on, but that’s not the purpose of this post. Its only but a guide as you will discover other topic and concepts I didn’t talk about here.</p><p>Have fun learning 👋. See you around.</p><p><em>Originally published at </em><a href="https://codelikesuraj.hashnode.dev/getting-started-in-backend-development-a-beginners-guide"><em>https://codelikesuraj.hashnode.dev</em></a><em> on June 5, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fac9cd6b500" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple HTML form validation with PHP (a step-by-step guide)]]></title>
            <link>https://abdulbakisuraj.medium.com/simple-html-form-validation-with-php-a-step-by-step-guide-2cb909fe3658?source=rss-afca7482c03a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cb909fe3658</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html-form]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[forms]]></category>
            <dc:creator><![CDATA[Abdulbaki Suraj]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 11:32:46 GMT</pubDate>
            <atom:updated>2024-02-28T11:18:50.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HkjKeMzUAcAIsw-W" /></figure><p>In this tutorial, I’ll be showing you how to perform a simple HTML form processing/validation using PHP. For the tutorial, we will build a simple user form that request for their full name and displays a welcome text after the user has entered their details in the html form and submitted.</p><p>Let’s get started!</p><h3>1) Setting up your environment</h3><p>If you already have your test environment ready, you can skip this step and jump to <a href="https://codelikesuraj.hashnode.dev/php-form-processing-and-validation#file">creating the file.</a></p><p>For us to be able to properly view and test our application, we need to have some tools in place:</p><ul><li>A browser (I will be using <a href="https://www.google.com/chrome">Google Chrome Browser</a>): Any browser will do</li><li>A text editor (I am using <a href="https://www.sublimetext.com/3">Sublime Text 3</a>): This is to create, edit and save our code</li><li>A local web server installed (I use <a href="https://www.apachefriends.org/download.html">XAMPP</a> on windows 10): To simulate an http-server on your computer</li></ul><p>In case you run into some trouble setting up XAMPP, you can check out this <a href="https://www.ionos.com/digitalguide/server/tools/xampp-tutorial-create-your-own-local-test-server">tutorial</a>.</p><p>After all that is done, the next thing for you to do is to go into the <em>htdocs</em> folder inside your XAMPP installation directory (mine is — C:\xampp\htdocs) and create a new folder (I’ll name mine “form”). You can name it anything you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*nTgqkBpjoe0-TbGR" /></figure><p>Next, open Sublime Text 3 and create a new file (ctrl + n).</p><p>Copy and paste the following code into it.</p><pre>&lt;?php<br>echo (&quot;Hello world!&quot;);<br>?&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/0*NWQdve-nuemSv2fZ" /></figure><p>Then save it as index.php inside the folder you created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*GpkGX0t9VoFDR7Nf" /></figure><p>Next step after ensuring the XAMPP server is running is to go to your browser and type this into the URL bar <em>http://localhost/name_of_your_folder</em>. Your browser screen should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*wPQgEOcu8wIR1pzu" /></figure><p>If all goes well, you can proceed to the next step.</p><h3>2) Writing the HTML for the form</h3><p>In your index.php file, clear any previous code there and copy and paste the following into it.</p><pre>&lt;?php<br>/*php main code goes here*/<br>?&gt;<br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;My Form&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h2&gt;My form&lt;/h2&gt;<br>    &lt;form method=&quot;post&quot;&gt;<br>        &lt;?php <br>        /* php error and display code goes here */<br>        ?&gt;<br>        Name: <br>        &lt;input type=&quot;text&quot; name=&quot;username&quot;&gt;&lt;br&gt;&lt;br&gt;<br>        &lt;input type=&quot;submit&quot; name=&quot;submit_form&quot; value=&quot;SUBMIT&quot;&gt;<br>    &lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>This is just a simple html form with an input field and a submit button. After this is added, save (ctrl + s) again on the text editor and reload the page on the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*riFPwh6wHA_jwv35" /></figure><p>Cool, now we have our form, but typing stuffs into the box and clicking the submit button won’t do anything.</p><p>Alright, let’s move on to the real deal and probably what brought you here in the first place — creating a few lines of PHP 🐘 code.</p><h3>3) Writing the PHP test cases</h3><p>Note that in the HTML form earlier, our method attribute was “post” &lt;form method=&quot;post&quot;&gt;, this is how the data entered by the user is transferred to the server and we shall be making using of $_POST[&#39;name_in_form&#39;] function to retrieve our data. Here are some of the conditions we are going to be checking for:</p><ul><li>check if the user submitted an empty field — this will be checked using the <a href="https://www.w3schools.com/php/func_var_empty.asp">empty(str) function</a>,</li><li>check if the user submitted a numeric value — this will be checked using the <a href="https://www.w3schools.com/php/func_var_is_numeric.asp">is_numeric(str) function</a>,</li><li>check if the number of words submitted is less than 2 so as to ensure the user submits at least a first and a last name — this will be checked using the <a href="https://www.w3schools.com/php/func_string_str_word_count.asp">str_word_count(str) function</a>.</li></ul><p>Copy and paste the following code just below the line where you have /* php main code goes here */:</p><pre>if ( isset( $_POST[&#39;submit_form&#39;]))<br>{<br>    //create a variable to store the display message<br>    $display = &#39;&#39;;      <br><br>    //assign the value of $_POST[&#39;username&#39;] to $full_name variable<br>    $full_name = $_POST[&#39;username&#39;];<br><br>    //check if there is no data in the variable<br>    if ( empty($full_name))<br>    {<br>        $display = &quot;Error: Input is empty, please enter a name !&quot;;<br>    }<br><br>    //check if the data is a number<br>    else if ( is_numeric($full_name) )<br>    {<br>        $display = &quot;Error: Name cannot be numeric&quot;;<br>    }<br><br>    //check if the number of words is not less than two<br>    else if( str_word_count($full_name) &lt;= 1) <br>    {<br>        $display = &quot;Error: Please enter a valid first and last name&quot;;<br>    }<br><br>    //if all the above conditions are false<br>    else<br>    {<br>        $display = &quot;Hey &quot;.htmlentities($full_name).&quot;, you are awesome :)&quot;;<br>    }<br>}</pre><p>I added a lot of commenting in the code in other to make it self-explanatory.</p><p>And also copy the following code just below the line where you have /* php error and display code goes here */</p><pre>//display the variable if a value has been set<br>if ( isset($display))<br>{<br>    echo &quot;$display&quot;;<br>}</pre><p>The above code allows us to visually see the errors they encounter during the validation process.</p><p>To avoid PHP errors from disrupting the screen, the isset($display) condition is used to ensure the variable is set (that is, a value has been passed into it) before there is any reason to display anything.</p><p>Below are screenshots of the application displaying the errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*rYMo8aea9A1nkHzJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*5_pzSUdKUooJAoXI" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*J74zPtGpXH1UCvFH" /></figure><p>And here’s a bonus 😉 screenshot of me entering correct values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*PqOnUoQNS_8oRiF2" /></figure><p>Thank you for following me till the end of the tutorial and I hope you have learned something new too.</p><p><em>Originally published at </em><a href="https://codelikesuraj.hashnode.dev/php-form-processing-and-validation"><em>https://codelikesuraj.hashnode.dev</em></a><em> on September 20, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cb909fe3658" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>