<?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 Benediktus Satriya on Medium]]></title>
        <description><![CDATA[Stories by Benediktus Satriya on Medium]]></description>
        <link>https://medium.com/@bensatriya3?source=rss-2742753c73cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*szeD21ihO1K6cCjXpqLzWg.png</url>
            <title>Stories by Benediktus Satriya on Medium</title>
            <link>https://medium.com/@bensatriya3?source=rss-2742753c73cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:19:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bensatriya3/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[Kubeletto: The Free, Kubernetes-Powered Way to Deploy Your App in Minutes]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">If you&#x2019;ve been building on the web for more than a few years, you remember the golden age of &#x201C;just deploy it.&#x201D; git push heroku main and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@bensatriya3/kubeletto-the-free-kubernetes-powered-way-to-deploy-your-app-in-minutes-9804579748ef?source=rss-2742753c73cc------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@bensatriya3/kubeletto-the-free-kubernetes-powered-way-to-deploy-your-app-in-minutes-9804579748ef?source=rss-2742753c73cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9804579748ef</guid>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubeletto]]></category>
            <dc:creator><![CDATA[Benediktus Satriya]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 15:13:25 GMT</pubDate>
            <atom:updated>2026-07-12T15:16:08.585Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[CI/CD GitOps with Kubernetes and FluxCD]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.devops.dev/ci-cd-gitops-with-kubernetes-and-fluxcd-71433b67d178?source=rss-2742753c73cc------2"><img src="https://cdn-images-1.medium.com/max/2050/1*uXnJoC1xSHEBI6L7v5uUAQ.png" width="2050"></a></p><p class="medium-feed-snippet">By following this step-by-step guide, you&#x2019;ve learned how to set up a CI/CD GitOps workflow with Kubernetes and FluxCD.</p><p class="medium-feed-link"><a href="https://blog.devops.dev/ci-cd-gitops-with-kubernetes-and-fluxcd-71433b67d178?source=rss-2742753c73cc------2">Continue reading on DevOps.dev »</a></p></div>]]></description>
            <link>https://blog.devops.dev/ci-cd-gitops-with-kubernetes-and-fluxcd-71433b67d178?source=rss-2742753c73cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/71433b67d178</guid>
            <category><![CDATA[flux]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Benediktus Satriya]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 14:45:15 GMT</pubDate>
            <atom:updated>2026-07-15T09:17:02.218Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Deploy React/Vue.js Web Apps on a Single VM with Docker & Nginx]]></title>
            <link>https://medium.com/@bensatriya3/deploy-react-vue-js-web-apps-on-a-single-vm-with-docker-nginx-12cd4f103322?source=rss-2742753c73cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/12cd4f103322</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Benediktus Satriya]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 09:29:49 GMT</pubDate>
            <atom:updated>2024-12-27T10:39:56.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZN4Xi5LiqkxkGDVlzyh2PQ.jpeg" /></figure><p>Deploying modern web apps like React or Vue.js can seem daunting, but with Docker and Nginx, you can host multiple apps on a single VM efficiently and easy. This guide focuses on practical steps, starting with setting up a VM and ending with HTTPS-enabled deployments.</p><h3>Step 1: Set Up Your Virtual Machine</h3><p>For this tutorial, we’ll use AWS EC2, but you can adapt these steps for GCP, DigitalOcean, or other providers.</p><h3>AWS EC2 Setup</h3><ol><li>Log in to your AWS account and navigate to the EC2 Dashboard.</li><li>Launch an instance:</li></ol><ul><li>Choose an Ubuntu Server 20.04 LTS AMI.</li><li>Select an instance type (e.g., t2.micro for free tier).</li><li>Configure security group to allow SSH (port 22) and HTTP/HTTPS (ports 80 and 443).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5LoWeRVObWiBWbjRwbZgQ.png" /><figcaption>EC2 Instance Running</figcaption></figure><p>3. Connect to the instance using SSH:</p><pre>chmod 400 &quot;your-key.pem&quot;</pre><pre>ssh -i your-key.pem ubuntu@your-ec2-public-ip</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugtvouuAuTt6T6GkEyMxLg.png" /><figcaption>Ubuntu VM</figcaption></figure><p>If your terminal displays the following output, it indicates that you have successfully connected to your Ubuntu VM.</p><h3>Install Nginx &amp; Docker Engine on VM</h3><ol><li>Update packages</li></ol><pre>sudo apt update &amp;&amp; sudo apt upgrade -y</pre><p>2. Install Nginx</p><pre>sudo apt install -y nginx</pre><pre>sudo systemctl start nginx<br>sudo systemctl enable nginx</pre><p>3. Install Docker</p><pre>curl -fsSL https://get.docker.com -o get-docker.sh<br>sudo sh get-docker.sh</pre><p>To check if Nginx is running, use the command:</p><pre>sudo systemctl status nginx</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgZWlRybz9oMkf5tAI1Dbg.png" /><figcaption>Nginx Service</figcaption></figure><p>For Docker, verify the installation by running:</p><pre>sudo docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9U76WzATgqA2z7P4qL6lRg.png" /><figcaption>Docker Images</figcaption></figure><p>Since we haven’t done anything yet and only completed the installation, the output will likely be empty. If your terminal shows these expected results, it means the installation of Nginx and Docker was successful.</p><h3>Step 2: Configure Your Domain</h3><p>We’ll use Namecheap as an example for domain registration and Cloudflare for DNS management. However, you can choose any domain provider of your preference.</p><h3>Domain Configuration</h3><ol><li>Purchase a domain from your preferred domain registrar (e.g., Namecheap, GoDaddy, or Google Domains). In this tutorial, we use Namecheap.</li><li>Log in to Cloudflare and <strong>add your domain</strong>:</li></ol><ul><li>Configure the nameservers provided by Cloudflare in your domain provider’s dashboard (e.g., in Namecheap’s DNS settings)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0qoZb1CvxFXxP0vsVgnrA.png" /><figcaption>Nameservers DNS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zeU3SV9yB5eNUN1TEl1Rg.png" /><figcaption>Domain List</figcaption></figure><p>After adding your domain to Cloudflare and updating your domain provider’s nameservers to point to mario.ns.cloudflare.com and raina.ns.cloudflare.com, it can take up to a couple of hours for the changes to propagate globally. Once successful, your domain will appear as &quot;Active&quot; on the Cloudflare dashboard. To configure DNS records for your domain, simply click on the desired domain within the dashboard.</p><p>3. Set up an A record in Cloudflare pointing your domain to the VM’s public IP address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgYIqHyPKafRI5ZBi6Xq4A.png" /><figcaption>Set A Record Subdomain</figcaption></figure><p>if you plan to deploy more applications with unique subdomains, simply add record again, using the desired subdomain name in the “Name” field each time. All subdomains will point to the same VM’s public IP address since they reside on the same server.</p><h3>Step 3: Build Your Web Apps with Docker</h3><p>We’ll build two apps: a React app and a Vue.js app.</p><h3>Prepare the React App</h3><ol><li>Add Dockerfile in your React root project</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQ-jBJxSUO8_TqTJ6Wc8WA.png" /><figcaption>Reactjs Web</figcaption></figure><p>2. After setting the Dockerfile in the root project, build the Docker image</p><pre>docker build -t reactjs-app .</pre><p>3. Push the image to Docker Hub (or any container registry)</p><pre>docker tag reactjs-app your-dockerhub-username/reactjs-app<br>docker push your-dockerhub-username/reactjs-app</pre><h3>Prepare the Vue.js App</h3><ol><li>Add Dockerfile in your Vue.js root project</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AniFjQ-tV3kYTcl3dbPO_Q.png" /><figcaption>Vuejs Web</figcaption></figure><p>2. After setting the Dockerfile in the root project, build the Docker image</p><pre>docker build -t vuejs-app .</pre><p>3. Push the image to Docker Hub (or any container registry)</p><pre>docker tag vuejs-app your-dockerhub-username/vuejs-app<br>docker push your-dockerhub-username/vuejs-app</pre><p>After pushing both images to the Docker Hub image registry, they should be visible in your Docker Hub repositories as shown in the image above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foQfz43B6JDECM2xZkBhmA.png" /></figure><h3>Step 4: Deploy Your Web Apps on VM</h3><ol><li>Connect to the instance VM via SSH. If you forget how to do this, refer back to Step 1</li><li>Pull both images, vuejs-app and reactjs-app, into the VM</li></ol><pre>sudo docker pull beneboba/reactjs-app</pre><pre>sudo docker pull beneboba/vuejs-app</pre><p>To check the images, you can use the command sudo docker images. This will display the list of images as shown in the image above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cqg7dTkIlWgvS-nbXgf-Q.png" /><figcaption>Docker Images</figcaption></figure><p>Run containers to serve the reactjs app and the vuejs app</p><pre>sudo docker run --name react-app -d -p 8000:80 beneboba/reactjs-app</pre><pre>sudo docker run --name vue-app -d -p 9000:80 beneboba/vuejs-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJkpG1wkmMRQEht5YFQ43Q.png" /><figcaption>Running Container</figcaption></figure><h3>Step 5: Configure Nginx as a Reverse Proxy</h3><ol><li>Create symbolic links for each app’s configuration</li></ol><p><strong>ReactJs App</strong></p><pre>sudo nano /etc/nginx/sites-available/react-app</pre><p>Add the following:</p><pre>server {<br>    listen 80;<br>    server_name reactjs.benelabs.fun;<br><br>    location / {<br>        proxy_pass http://localhost:8000;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>    }<br>}</pre><p><strong>VueJs App</strong></p><pre>sudo nano /etc/nginx/sites-available/vue-app</pre><p>Add the following:</p><pre>server {<br>    listen 80;<br>    server_name vuejs.benelabs.fun;<br>    location / {<br>        proxy_pass http://localhost:9000;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>    }<br>}</pre><p>2. Enable the configurations</p><pre>sudo ln -s /etc/nginx/sites-available/react-app /etc/nginx/sites-enabled/<br>sudo ln -s /etc/nginx/sites-available/vue-app /etc/nginx/sites-enabled/</pre><p>3. Test and reload Nginx</p><pre>sudo nginx -t<br>sudo systemctl restart nginx</pre><p>Great! 😊 Now both your web applications are accessible from the internet. I tested access from Safari using the hostnames configured, vuejs.benelabs.fun and reactjs.benelabs.fun. However, for enhanced security, we need to set up SSL certificates for HTTPS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRc2E0v8iIufgsXQxeERrQ.png" /><figcaption>vuejs.benelabs.fun</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zx0Trhpjr4cLL57dXqQERg.png" /><figcaption>reactjs.benelabs.fun</figcaption></figure><h3>Step 6: Enable HTTPS with Let’s Encrypt</h3><ol><li>Install Certbot:</li></ol><pre>sudo apt install -y certbot python3-certbot-nginx</pre><p>2. Obtain certificates for both domains:</p><pre>sudo certbot --nginx -d reactjs.benelabs.fun</pre><pre>sudo certbot --nginx -d vuejs.benelabs.fun</pre><p>3. Verify HTTPS is working:</p><p>Visit https://reactjs.benelabs.fun and https://vuejs.benelabs.fun in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPNnJvrT84aJWPNTplL3qQ.png" /><figcaption>HTTPS vuejs.benelabs.fun</figcaption></figure><h3>Conclusion</h3><p>Congratulations! 🥳 You’ve deployed multiple web apps on a single VM using Docker and Nginx. This setup is scalable and cost-effective, ideal for hosting modern web apps. Share your success in the comments or reach out with questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12cd4f103322" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building API with Test-Driven Development in Go: A Practical Guide | Part 1]]></title>
            <link>https://medium.com/codex/building-api-with-test-driven-development-in-go-a-practical-guide-part-1-ad56f1535353?source=rss-2742753c73cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad56f1535353</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <dc:creator><![CDATA[Benediktus Satriya]]></dc:creator>
            <pubDate>Tue, 07 May 2024 04:32:06 GMT</pubDate>
            <atom:updated>2024-05-08T10:31:43.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfzRIFMWazylc-5eacxtZQ.png" /></figure><h3>What is Test Driven Development (TDD)?</h3><p>Test-Driven Development (TDD) is a software development process where you write tests for your code before you write the actual implementation. The process typically follows these steps:</p><ol><li><strong>Write a Test:</strong> Before writing any code, you first write a test that describes the behavior you want to implement. This test will initially fail because the corresponding code hasn’t been written yet.</li><li><strong>Run the Test:</strong> Execute all the tests you’ve written so far. Since the new test is supposed to fail (as you haven’t implemented the feature yet), it should indeed fail. This ensures that the test is valid and that it’s actually testing what you intend it to.</li><li><strong>Write the Code:</strong> Now you write the code necessary to make the test pass. You’re essentially writing code to fulfill the requirements defined by the test.</li><li><strong>Run the Tests Again:</strong> After writing the code, you rerun all the tests. If everything is implemented correctly, the new test you just wrote should now pass, along with all the existing tests. If any test fails, it means either your new code is incorrect or your test is flawed.</li><li><strong>Refactor:</strong> Once all tests pass, you may refactor your code. Refactoring involves restructuring your code without changing its external behavior.</li></ol><p>This iterative cycle continues: write a test, watch it fail, write code to make it pass, and then refactor. This process helps to ensure that your codebase remains maintainable, as it encourages small. It also helps in catching bugs early in the development process, leading to more robust and reliable software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*C6MKQSopwy3AIp2UcDABDg.png" /><figcaption><em>source image: </em><a href="https://marsner.com/blog/why-test-driven-development-tdd/">https://marsner.com/blog/why-test-driven-development-tdd/</a></figcaption></figure><p><strong>Prerequisites</strong></p><p>Before we begin, ensure that you have Go installed on your machine. If not, you can download and install it from the official Go website (golang.org).</p><p>Additionally, familiarity with RESTful API development in Go would be beneficial. If you haven’t yet explored this topic, feel free to read my article for insights.</p><blockquote><a href="https://medium.com/@bensatriya3/deep-dive-into-go-crafting-a-crud-restful-api-without-frameworks-920cd6eab3be">Deep Dive into Go: Crafting a CRUD RESTful API Without Frameworks</a></blockquote><p><strong>Setup Project</strong></p><p>To get started, let’s create a new directory for our project. Open your terminal and run the following commands:</p><pre>mkdir tdd<br>cd tdd</pre><pre>go mod init tdd</pre><p>This will create a go.mod file in your project directory, enabling Go modules for managing dependencies.</p><p>To install dependencies for testing and the PostgreSQL driver, you can use Go modules. Open your terminal and execute the following commands:</p><pre>go get github.com/stretchr/testify<br><br>go get github.com/lib/pq</pre><p>These commands will fetch and install the testify library for testing and the lib/pq package, which is the PostgreSQL driver for Go.</p><p><strong>Setup Database</strong><br>Create a database named “tdd” in your local PostgreSQL.</p><pre>sudo docker exec -it postgres16 createdb --username=root --owner=root tdd</pre><p>Now, let’s create a table in your PostgreSQL database. We’ll create a simple table named users with two columns: id , username, and password .</p><pre>CREATE TABLE users (<br>                       id SERIAL PRIMARY KEY,<br>                       username VARCHAR(50) UNIQUE NOT NULL,<br>                       password VARCHAR(100) NOT NULL<br>);</pre><p>Add this query to your migration up SQL, then run it.</p><pre>migrate -path db/migrations -database &quot;postgresql://root:root@localhost:5432/tdd?sslmode=disable&quot; -verbose up</pre><p>Nice! Now the database is all set.</p><p><strong>Setup Database for Test Case</strong></p><p>Create function <strong><em>TestMain(m *testing.M)</em></strong> is a special function in Go testing package that allows setup and teardown code to be run for all tests in a package. It’s typically used for common setup and teardown tasks.</p><blockquote>database.go</blockquote><pre>type DB struct {<br> db *sql.DB<br>}<br><br>func NewDB(db *sql.DB) *DB {<br> return &amp;DB{<br>  db: db,<br> }<br>}</pre><blockquote>setup_test.go</blockquote><pre><br>var (<br> testDB *sql.DB<br>)<br><br>const (<br> postgresDNS = &quot;postgres://root:root@localhost:5432/tdd?sslmode=disable&quot;<br>)<br><br>func TestMain(m *testing.M) {<br> db, err := sql.Open(&quot;postgres&quot;, postgresDNS)<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> err = db.Ping()<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> testDB = db<br><br> // Truncate the users table before running the tests<br> _, err = testDB.Exec(&quot;TRUNCATE users&quot;)<br> if err != nil {<br>  log.Fatal(err)<br><br> }<br><br> code := m.Run()<br><br> // Close the database connection after running the tests<br> err = testDB.Close()<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> os.Exit(code)<br>}</pre><p>This setup ensures that before running any tests, a clean database state is established with an empty users table, and after running the tests, the database connection is properly closed. This helps in isolating tests and ensuring that they don&#39;t interfere with each other&#39;s state.</p><p><strong>Writing Your First Test</strong></p><p>In our first simple case, we create a test for user creation. We assume that if we input correct data, the result should match what we inserted previously.</p><blockquote>slqstore/create_user_test.go</blockquote><pre><br>func TestCreateUser(t *testing.T) {<br><br> sqlStore := NewDB(testDB)<br><br> user := &amp;domain.User{<br>  Username: &quot;test&quot;,<br>  Password: &quot;password&quot;,<br> }<br><br> createdUser, err := sqlStore.CreateUser(user)<br><br> assert.Nil(t, err)<br> assert.NotNil(t, createdUser)<br> assert.Equal(t, user.Username, createdUser.Username)<br> assert.Equal(t, user.Password, createdUser.Password)<br>}</pre><p>We know this should throw an error because we haven’t created a struct for <strong><em>domain.User</em></strong> and the <strong><em>CreateUser</em></strong> method yet. But it’s okay, let’s run it. After all, this is TDD! 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*rHR4yyIoy5ztyg74RiPUkQ.png" /></figure><p>Awesome, we got a message from machine compiler. Now lets fix it!</p><blockquote>domain/model.go</blockquote><pre>type User struct {<br> ID       int    `json:&quot;id&quot;`<br> Username string `json:&quot;username&quot;`<br> Password string `json:&quot;password&quot;`<br>}</pre><blockquote>sqlstore/user.go</blockquote><pre><br>var (<br> sqlCreateUser = `INSERT INTO users (username, password) VALUES ($1, $2) RETURNING id`<br>)<br><br><br>func (d *DB) CreateUser(user *domain.User) (*domain.User, error) {<br><br> // Query create user and then scan the id<br> err := d.db.QueryRow(sqlCreateUser, user.Username, user.Password).<br>  Scan(&amp;user.ID)<br><br> // Return error if any<br> if err != nil {<br>  return nil, err<br> }<br><br> // Return the user<br> return user, nil<br>}</pre><p>Now, let’s run the test again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*43JWZVU_-ZbWuWI7Nf4vpw.png" /></figure><p>Great! The test passed.</p><p>If you encounter an error or the test doesn’t pass, you should fix it until it passes. Then, you can proceed to create a new test case.</p><p><strong>Second Test Case</strong></p><p>I want my API to throw an error if a user submits a username that already exists in the database.</p><pre>func TestCreateUserDuplicateUsername(t *testing.T) {<br> sqlStore := NewDB(testDB)<br><br> user := &amp;domain.User{<br>  Username: &quot;test&quot;,<br>  Password: &quot;password&quot;,<br> }<br><br> // Create a user<br> _, err := sqlStore.CreateUser(user)<br> assert.Nil(t, err)<br><br> // Create another user with the same username<br> createUserTwo, err := sqlStore.CreateUser(user)<br> <br> assert.NotNil(t, err)<br> assert.Nil(t, createUserTwo)<br>}</pre><p>Now, let’s run the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*L1NEcbmiBzXPbPZt7uOkzw.png" /></figure><p>What! Why no error? Oh, it’s because we created the table with the unique keyword. The database automatically throws an error if we try to insert the same username twice since usernames cannot be duplicated.</p><p>But in TDD, we should create a failing test; that test is not valid. Now let’s adjust the test until it fails.</p><pre><br>func TestCreateUserDuplicateUsername(t *testing.T) {<br> // ... your code ...<br><br> assert.NotNil(t, err)<br> // Added this, Check if the error should equal with ErrDuplicateUsername<br> assert.Equal(t, err, domain.ErrDuplicateUsername)<br> assert.Nil(t, createUserTwo)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wxnv15d-uQGJRi99ye9Rw.png" /></figure><p>Okay, we received the message. Let’s fix it again.</p><blockquote><em>Add custom </em><strong>errors</strong><em><br></em>domain/errors.go</blockquote><pre>import &quot;errors&quot;<br><br>var (<br> ErrDuplicateUsername = errors.New(&quot;duplicate username&quot;)<br>)</pre><blockquote><em>Fix the error handle on method </em><strong>CreateUser<em><br></em></strong>sqlstore/user.go</blockquote><pre>func (d *DB) CreateUser(user *domain.User) (*domain.User, error) {<br> // your code ..<br><br> // Handle unique pqError code with 23505 is unique constraint violation<br> pgErr, ok := err.(*pq.Error)<br> if ok &amp;&amp; pgErr.Code == &quot;23505&quot; {<br>  // Handle unique constraint violation error here<br>  // For example, you can return a custom error indicating the username is already taken<br>  return nil, domain.ErrDuplicateUsername<br> }<br><br> // your code ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*N8-U7wVIGbwAEnyRRSN4jA.png" /></figure><p>Cool, all passed.</p><p>However, if we notice that the <strong>coverage is less than 100%</strong>, it’s because we haven’t written tests to cover all possible error scenarios, excluding the case of duplicate unique fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*qDC2IkxafFjS0Nw-YK4k9Q.png" /></figure><p>Now, let’s create the tests to achieve 100% coverage and handle all possible scenarios.</p><pre><br>func TestThrowErrorInvalidSQL(t *testing.T) {<br> oldSql := sqlCreateUser<br><br> sqlStore := NewDBTest(testDB)<br><br> user := &amp;entity.User{<br>  Username: &quot;bene&quot;,<br>  Password: &quot;password&quot;,<br> }<br><br> // Inject invalid SQL<br> sqlCreateUser = `invalid sql query`<br><br> createdUser, err := sqlStore.CreateUser(user)<br> assert.Nil(t, createdUser)<br> assert.NotNil(t, err)<br><br> // Reset the sqlCreateUser<br> sqlCreateUser = oldSql<br>}</pre><p>Let’s run the tests with coverage, and it’s cool to see that we have achieved 100% coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4DH_yVFZrT_TMq5HIvHHA.png" /></figure><p>Congratulations! We’ve successfully built a repository for storing data in PostgreSQL using test-driven development. Additionally, we’ve learned how to achieve <em>100% test coverage</em> in Go.</p><p>This article isn’t finished yet as we haven’t built the API.</p><blockquote><strong>For part 2, I’ll be working on it soon. Have a great day!</strong></blockquote><p>The source code you can access is <a href="https://github.com/benebobaa/test-driven-development">https://github.com/benebobaa/test-driven-development</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad56f1535353" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/building-api-with-test-driven-development-in-go-a-practical-guide-part-1-ad56f1535353">Building API with Test-Driven Development in Go: A Practical Guide | Part 1</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking API Performance: Go Fiber vs. Java SpringBoot vs. Express.js]]></title>
            <link>https://blog.devops.dev/benchmarking-api-performance-go-fiber-vs-java-springboot-vs-express-js-28679a8c8dc8?source=rss-2742753c73cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/28679a8c8dc8</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Benediktus Satriya]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 20:27:55 GMT</pubDate>
            <atom:updated>2026-10-27T10:16:24.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xSzc8Ifa1wArRDQMIlidQ.gif" /></figure><p><strong>Introduction</strong></p><p>In today’s rapidly evolving technological landscape, choosing the right framework for developing APIs is crucial for ensuring optimal performance and scalability. With numerous options available, developers often face the dilemma of selecting the most suitable framework for their projects. In this article, we embark on a journey to benchmark the performance of three popular frameworks: Go Fiber, Java SpringBoot, and Express.js.</p><p><strong>Benchmarking Setup</strong></p><p>To conduct a fair comparison, we set up a standardized environment using a Virtual Private Server (VPS) with the following specifications: 1 core CPU and 1GB RAM. I use Docker to containerize each framework, ensuring consistency across deployments. Additionally, we utilized Grafana and Prometheus for monitoring server metrics, while k6 served as the load testing tool.</p><blockquote><strong>Let’s Get Started</strong></blockquote><blockquote><strong>Setting up the Docker images</strong></blockquote><p>For testing purposes, I implemented the “Hello World” APIs in Go Fiber, Java SpringBoot, and Express.js. An interesting observation was the significant difference in image sizes among them. Java SpringBoot had the largest size, weighing in at 459MB, followed by Express.js at 138MB, while Go Fiber was the most lightweight at just 16.5MB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wAm1sEHTWgpogKcfHTdkTw.png" /></figure><blockquote><strong>Load Testing with k6</strong></blockquote><p>To simulate real-world traffic and gauge the performance of our API endpoints, we employ k6, a powerful open-source load testing tool. The k6 script provided below is tailored to our benchmarking scenario, aiming to stress-test each API implementation under varying levels of concurrent user traffic.</p><pre>import http from &#39;k6/http&#39;;<br>import { check, sleep } from &#39;k6&#39;;<br><br>export let options = {<br>  stages: [<br>    { duration: &#39;1m&#39;, target: 200 }, // Ramp up to 200 users over 1 minute<br>    { duration: &#39;3m&#39;, target: 500 }, // Stay at 500 users for 3 minutes<br>    { duration: &#39;1m&#39;, target: 300 }, // Ramp down to 300 users over 1 minute<br>  ],<br>  thresholds: {<br>    http_req_duration: [&#39;p(95)&lt;500&#39;], // 95% of requests should be below 500ms<br>  },<br>};<br><br>export default function () {<br>  let res = http.get(&#39;http://--ip address--:8080/fiber&#39;);<br>  check(res, {<br>    &#39;status is 200&#39;: (r) =&gt; r.status === 200,<br>    &#39;transaction time is OK&#39;: (r) =&gt; r.timings.duration &lt; 500,<br>  });<br>  sleep(1); // Add a short sleep to control the request rate<br>}</pre><ul><li>The options object defines the load testing scenario with specified stages:</li></ul><ol><li>Ramp up to 200 users over 1 minute.</li></ol><p>2. Maintain 500 users for 3 minutes.</p><p>3. Ramp down to 300 users over 1 minute.</p><ul><li>Set a threshold to ensure that 95% of requests have a duration of less than 500ms, indicating acceptable performance.</li></ul><p><strong>Analysis of Load Testing Results</strong></p><blockquote><strong>Express Js</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBn_z4-13ZdDpWN--O3brg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKZ_SUXKZwdQ4CsXguDvLA.png" /></figure><p><strong><em>http_req_duration : 20.31 ms</em></strong></p><p><strong><em>http_reqs : 91259 -&gt; 303 req/s</em></strong></p><blockquote><strong>Java SpringBoot</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHVEDoRDkh5aPdnMEyHZew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuOcBGVX4w9GG8SbnfKJVQ.png" /></figure><p><strong><em>http_req_duration : 24.16 ms</em></strong></p><p><strong><em>http_reqs : 90893 -&gt; 301 req/s</em></strong></p><blockquote><strong>Go Fiber</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7PNYbkprpcxxbzWZu8okA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QDyHrHzDe76_MDQ6HT8pQ.png" /></figure><p><strong><em>http_req_duration : 20.59 ms</em></strong></p><p><strong><em>http_reqs : 91207 -&gt; 303 req/s</em></strong></p><p>In the load testing results, we observed that Go Fiber had a few requests (specifically 5) that exceeded the 500ms threshold, unlike Express.js and Java SpringBoot, which didn’t encounter any such outliers. This suggests a slight inconsistency in Go Fiber’s performance compared to the other frameworks.</p><h4>Express.js</h4><ul><li>Average Request Duration: 20.31 ms</li><li>Requests per Second: 303 req/s</li></ul><p>Resource Utilization: <strong><em>CPU: Max 28%, </em>RAM: 61%</strong></p><p>Express.js demonstrates commendable performance with an average request duration of 20.31 ms and handling a throughput of 303 requests per second. The resource utilization remains within acceptable limits, with the CPU peaking at 28% and RAM at 61%.</p><h4>Java SpringBoot</h4><ul><li>Average Request Duration: 24.16 ms</li><li>Requests per Second: 301 req/s</li></ul><p>Resource Utilization: <strong>CPU: Max 23%, RAM: 72%</strong></p><p>Java SpringBoot exhibits slightly higher request durations compared to Express.js, with an average of 24.16 ms. It maintains a throughput of 301 requests per second while experiencing moderate resource utilization, with CPU peaking at 23% and RAM at 72%.</p><h4>Go Fiber</h4><ul><li>Average Request Duration: 20.59 ms</li><li>Requests per Second: 303 req/s</li></ul><p>Resource Utilization: <strong>CPU: Max 28%, RAM: 57%</strong></p><p>Go Fiber showcases similar performance to Express.js, with an average request duration of 20.59 ms and handling a throughput of 303 requests per second. Resource utilization remains efficient, with the CPU peaking at 28% and RAM at 57%.</p><h3>Conclusion</h3><ul><li>Express.js: Offers excellent performance with low request durations and efficient resource utilization.</li><li>Java SpringBoot: Provides stable performance, albeit with slightly higher request durations and relatively higher resource consumption.</li><li>Go Fiber: Stands out with comparable performance to Express.js and efficient resource utilization, making it an attractive choice for lightweight and high-performance API development.</li></ul><p>These findings underscore the importance of considering not only performance metrics but also resource efficiency when selecting a framework for API development. Ultimately, the choice depends on specific project requirements and preferences, with each framework offering distinct advantages and trade-offs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28679a8c8dc8" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/benchmarking-api-performance-go-fiber-vs-java-springboot-vs-express-js-28679a8c8dc8">Benchmarking API Performance: Go Fiber vs. Java SpringBoot vs. Express.js</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient API Data Handling in Flutter: Implementing Pagination with Provider]]></title>
            <link>https://medium.com/@bensatriya3/efficient-api-data-handling-in-flutter-implementing-pagination-with-provider-772462f95a18?source=rss-2742753c73cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/772462f95a18</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Benediktus Satriya]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 16:15:37 GMT</pubDate>
            <atom:updated>2024-03-26T17:18:37.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHDgqFff3trH_j8ldvCvNQ.png" /></figure><p><strong>Introduction</strong></p><p>In modern app development, efficient data handling is paramount, especially when dealing with large datasets from APIs. Flutter, with its robust framework, provides various state management solutions to handle data effectively. Among them, Provider stands out for its simplicity and scalability. In this article, we’ll explore how to implement pagination using Provider in Flutter to manage API data efficiently.</p><p><strong>Understanding Pagination</strong></p><p>Pagination is a technique used to split large datasets into smaller, manageable chunks, thus enhancing performance and user experience. Instead of loading all data at once, pagination fetches data incrementally, typically in response to user interactions like scrolling or button clicks.</p><p><strong>Setting Up the Project</strong></p><p>Before diving into implementation, let’s set up a Flutter project and install necessary dependencies. Ensure you have Flutter SDK installed on your system.</p><pre>flutter create pagination-simple-provider<br>cd pagination-simple-provider</pre><p>Next, add the required dependencies in your pubspec.yaml file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  cupertino_icons: ^1.0.6<br>  provider: ^6.1.2<br>  http: ^1.2.1</pre><p>Run flutter pub get to install the dependencies.</p><p><strong>Implementing Pagination with Provider</strong></p><blockquote>home_state.dart</blockquote><p>Let’s begin by comprehending the state management setup for our pagination implementation. In the home_state.dart file, we define the HomeState class:</p><pre>enum HomeStatus { initial, success, error }<br><br>class HomeState&lt;T&gt; {<br>  final HomeStatus status;<br>  final List&lt;T&gt; contacts;<br>  final bool hasReachedMax;<br><br>  const HomeState({<br>    this.status = HomeStatus.initial,<br>    this.contacts = const [],<br>    this.hasReachedMax = false,<br>  });<br><br>  HomeState&lt;T&gt; copyWith({<br>    HomeStatus? status,<br>    List&lt;T&gt;? contacts,<br>    bool? hasReachedMax,<br>  }) {<br>    return HomeState(<br>      status: status ?? this.status,<br>      contacts: contacts ?? this.contacts,<br>      hasReachedMax: hasReachedMax ?? this.hasReachedMax,<br>    );<br>  }<br>}d</pre><p>The HomeState class encapsulates the state of the home screen. It includes three main properties:</p><ul><li>status: Represents the current status of data retrieval, as defined by the HomeStatus enum.</li><li>contacts: Stores the list of data items, such as contacts in this case. It&#39;s parameterized by type T, allowing flexibility in the type of data stored.</li><li>hasReachedMax: Indicates whether the maximum limit of data has been reached.</li></ul><p>The constructor initializes these properties with default values, where status is set to initial, contacts is an empty list, and hasReachedMax is false by default. The copyWith method allows for creating a new instance of HomeState by optionally updating its properties.</p><blockquote>home_page.dart</blockquote><p>In Flutter, the HomePage class represents the main screen of an application. This class is responsible for displaying UI elements and handling user interactions.</p><pre>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br>  <br>class _HomePageState extends State&lt;HomePage&gt; {<br>  final _scrollController = ScrollController();<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _scrollController.addListener(_onScroll);<br>  }<br><br>  @override<br>  void dispose() {<br>    _scrollController<br>      ..removeListener(_onScroll)<br>      ..dispose();<br>    super.dispose();<br>  }<br><br>  void _onScroll() {<br>    if (_isBottom) {<br>      context.read&lt;HomeProvider&gt;().getContacts();<br>    }<br>  }<br><br>  bool get _isBottom {<br>    if (!_scrollController.hasClients) return false;<br>    final maxScroll = _scrollController.position.maxScrollExtent;<br>    final currentScroll = _scrollController.offset;<br>    return currentScroll &gt;= (maxScroll * 0.99);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    // UI implementation<br>  }<br>}</pre><p>The HomePage class is defined as a StatefulWidget and contains the logic for managing the state and building the UI of the home page. Here&#39;s a breakdown of key elements:</p><p>Scroll Controller:</p><ul><li>An instance of ScrollController is created to manage scrolling behavior.</li><li>In the initState method, the scroll controller is initialized and set to listen for scroll events.</li><li>In the dispose method, the scroll controller is disposed of to release resources when the widget is removed from the widget tree.</li></ul><p>Scroll Event Handling:</p><ul><li>The _onScroll method is called whenever the user scrolls the page.</li><li>If the user has scrolled to the bottom of the page (_isBottom), the getContacts method of the HomeProvider is called to fetch more data.</li></ul><p>Helper Method:</p><ul><li>_isBottom is a helper method that checks if the user has scrolled to the bottom of the page.</li></ul><pre>return Scaffold(<br>      // AppBar implementation <br>      body: Consumer&lt;HomeProvider&gt;(<br>        builder: (context, state, child) {<br>          if (state.homeState.status == HomeStatus.initial) {<br>            return const Center(child: CircularProgressIndicator());<br>          }<br>          if (state.homeState.status == HomeStatus.error) {<br>            return const Center(child: Text(&quot;Failed to fetch posts&quot;));<br>          }<br>          if (state.homeState.status == HomeStatus.success) {<br>            if (state.homeState.contacts.isEmpty) {<br>              return const Center(child: Text(&quot;No posts&quot;));<br>            }<br>            return ListView.builder(<br>              controller: _scrollController,<br>              itemCount: state.homeState.hasReachedMax<br>                  ? state.homeState.contacts.length<br>                  : state.homeState.contacts.length + 1,<br>              itemBuilder: (context, index) {<br>                return index &gt;= state.homeState.contacts.length<br>                    ? const Center(<br>                        child: CircularProgressIndicator(),<br>                      )<br>                    : Card(<br>                        child: ListTile(<br>                          leading: CircleAvatar(<br>                            child: Text(<br>                                state.homeState.contacts[index].id.toString()),<br>                          ),<br>                          title: Text(state.homeState.contacts[index].title),<br>                        ),<br>                      );<br>              },<br>            );<br>          }<br>          return const Center(child: CircularProgressIndicator());<br>        },<br>      ),<br>    );</pre><p>Specifically, it utilizes the Consumer widget from the provider package to listen for changes in the HomeProvider state and rebuilds the UI accordingly.</p><p><em>Status Initial</em></p><ul><li>Checks if the status of the HomeState within the HomeProvider is initial.</li><li>If the status is initial, it returns a CircularProgressIndicator widget centered on the screen, indicating that data is being fetched.</li></ul><p><em>Status Errror</em></p><ul><li>Checks if the status of the HomeState is error.</li><li>If the status is error, it returns a Text widget centered on the screen with the message &quot;Failed to fetch posts,&quot; indicating that there was an error while fetching data.</li></ul><p><em>Status Success</em></p><ul><li>If the status is success and there are posts to display, it returns a ListView.builder widget.</li><li>The ListView.builder dynamically creates a list of widgets based on the length of the contacts list.</li><li>If the user scrolls to the end of the list (index &gt;= state.homeState.contacts.length), it displays a CircularProgressIndicator widget at the center, indicating that more data is being fetched.</li><li>Otherwise, it constructs a Card widget for each post, displaying the post&#39;s ID and title using a CircleAvatar and Text widget respectively.</li></ul><blockquote>home_provider.dart</blockquote><pre><br><br>class HomeProvider with ChangeNotifier {<br>  final _postLimit = 20;<br><br>  var homeState = const HomeState&lt;Post&gt;();<br><br>  Future&lt;void&gt; getContacts() async {<br>    // implementation get contacts list<br>  }<br><br>  // fetching api<br>  Future&lt;List&lt;Post&gt;&gt; _fetchPosts([int startIndex = 0]) async {<br>    // implementation fetching api with http client<br>  }<br>}</pre><ul><li>The HomeProvider class is defined as a ChangeNotifier, enabling it to notify its listeners (typically UI components) when its state changes.</li><li>It has a _postLimit constant representing the maximum number of posts to fetch.</li><li>The homeState variable holds the current state of the home screen. Initially, it&#39;s set to an empty state (HomeStatus.initial) with no contacts and not reaching the maximum limit.</li></ul><pre>Future&lt;void&gt; getContacts() async {<br>  try {<br>    if (homeState.status == HomeStatus.initial) {<br>      final posts = await _fetchPosts();<br>      homeState = homeState.copyWith(<br>        status: HomeStatus.success,<br>        contacts: posts,<br>        hasReachedMax: posts.length &lt; _postLimit,<br>      );<br>    } else {<br>      final posts = await _fetchPosts(homeState.contacts.length);<br>      homeState = homeState.copyWith(<br>        status: HomeStatus.success,<br>        contacts: List.of(homeState.contacts)..addAll(posts),<br>        hasReachedMax: posts.length &lt; _postLimit,<br>      );<br>    }<br><br>    notifyListeners();<br>  } catch (e) {<br>    homeState = homeState.copyWith(<br>      status: HomeStatus.error,<br>    );<br>    notifyListeners();<br>  }<br>}</pre><ul><li>The getContacts method is responsible for fetching data. It&#39;s asynchronous, meaning it doesn&#39;t block the main UI thread while fetching data.</li><li>Inside the method, it checks the current status of homeState. If it&#39;s initial, it fetches initial data using _fetchPosts and updates homeState accordingly. If not, it fetches additional data based on the current list of contacts.</li><li>After updating homeState, it notifies its listeners about the state change using notifyListeners().</li></ul><pre>Future&lt;List&lt;Post&gt;&gt; _fetchPosts([int startIndex = 0]) async {<br>  await Future.delayed(const Duration(seconds: 1));<br>  final response = await client.get(<br>    Uri.https(<br>      &#39;jsonplaceholder.typicode.com&#39;,<br>      &#39;/posts&#39;,<br>      &lt;String, String&gt;{&#39;_start&#39;: &#39;$startIndex&#39;, &#39;_limit&#39;: &#39;$_postLimit&#39;},<br>    ),<br>  );<br>  if (response.statusCode == 200) {<br>    final body = json.decode(response.body) as List;<br>    return body<br>        .map((dynamic json) =&gt; Post.fromJson(json as Map&lt;String, dynamic&gt;))<br>        .toList();<br>  }<br>  throw Exception(&#39;error fetching posts&#39;);<br>}</pre><ul><li>The _fetchPosts method is a private method responsible for making HTTP requests to fetch posts from the API.</li><li>If the response status code is 200 (indicating success), it decodes the response body from JSON to a list of posts using json.decode.</li><li>It then maps each JSON object to a Post object using Post.fromJson.</li></ul><p>In summary, the HomeProvider class encapsulates the logic for fetching and managing data related to the home screen. It uses the ChangeNotifier pattern to notify its listeners (UI components) when its state changes, allowing for reactive UI updates.</p><blockquote>main.dart</blockquote><p>Before launching our application to ensure a smooth experience without any crashes or bugs, it’s crucial to set up our classes and providers within the main function.</p><pre>return MaterialApp(<br>  home: ChangeNotifierProvider(<br>    create: (context) =&gt; HomeProvider()..getContacts(),<br>    child: const HomePage(),<br>  ),<br>);</pre><p>The create parameter of ChangeNotifierProvider is utilized to instantiate the HomeProvider class and immediately call its getContacts() method to fetch initial data. The create parameter expects a function that returns an instance of the provided class, in this case, HomeProvider.</p><p><strong>Let’s now put our implementation to the test by trying out the app</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJoh_kZJ7Pt5-MeidhtEhg.gif" /></figure><p><strong>Conclusion</strong></p><p>By adopting pagination, developers can:</p><ol><li>Enhance Performance: By fetching and displaying data in smaller chunks, pagination reduces the load on the app and server, leading to faster response times and smoother user interactions.</li><li>Improve User Experience: Breaking down data into manageable pages allows users to navigate through content more easily, preventing information overload and ensuring a more enjoyable browsing experience.</li><li>Simplify Maintenance: Separating data retrieval and display logic into smaller, modular components makes code easier to understand, maintain, and debug, contributing to overall project scalability.</li></ol><p>However, it’s essential to consider potential drawbacks:</p><ol><li>Complexity: Implementing pagination requires additional logic to manage page state and navigation, which may introduce complexity, especially in larger projects.</li><li>Server-Side Requirements: Pagination relies on server-side support to retrieve data efficiently. Ensure that your backend API is capable of handling paginated requests.</li></ol><p>In conclusion, while pagination with Provider offers numerous benefits for managing API data in Flutter applications, developers must weigh these advantages against potential complexities and backend requirements. By carefully considering the needs of your application and leveraging the flexibility of Flutter, you can create efficient and user-friendly experiences for your users. Happy coding!</p><p>Full example code <a href="https://github.com/benebobaa/pagination-simple-provider"><em>https://github.com/benebobaa/pagination-simple-provider</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772462f95a18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Go: Crafting a CRUD RESTful API Without Frameworks]]></title>
            <link>https://medium.com/@bensatriya3/deep-dive-into-go-crafting-a-crud-restful-api-without-frameworks-920cd6eab3be?source=rss-2742753c73cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/920cd6eab3be</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[native]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[web-server]]></category>
            <dc:creator><![CDATA[Benediktus Satriya]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 08:29:06 GMT</pubDate>
            <atom:updated>2024-03-21T08:29:06.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HdZ436tQiN8px8z36PAOg.png" /></figure><p><strong>Introduction</strong></p><p>In today’s tech landscape, building RESTful APIs is a common task for developers. While there are numerous libraries and frameworks available to streamline this process, sometimes it’s beneficial to go back to basics and leverage the native capabilities of a programming language. In this tutorial, we’ll explore how to build a lightweight RESTful API in Go without relying on any external packages. By embracing Go’s simplicity and power, we’ll craft a clean and efficient API from scratch.</p><p><strong>Prerequisites</strong></p><p>Before we dive in, make sure you have Go installed on your machine. You can download and install it from the official Go website (golang.org). Basic familiarity with Go syntax and concepts like structs, functions, and HTTP handling will be helpful but not required. Our application will utilize a PostgreSQL database to store data. Ensure you have PostgreSQL installed on your machine.</p><p><strong>Setting Up Your Project</strong></p><p>To get started, let’s create a new directory for our project. Open your terminal and run the following commands:</p><pre>mkdir simple-native-api<br>cd simple-native-api</pre><pre>go mod init simple-native-api</pre><p>This will create a go.mod file in your project directory, enabling Go modules for managing dependencies.</p><p><strong>Setup Database</strong></p><p>Creating Table in PostgreSQL:</p><p>Now, let’s create a table in your PostgreSQL database. We’ll create a simple table named products with two columns: id , name , and price</p><pre>CREATE TABLE products (<br>    id SERIAL PRIMARY KEY,<br>    name VARCHAR(255) NOT NULL,<br>    price INTEGER NOT NULL,<br>    stock INTEGER NOT NULL<br>);</pre><p>Great!! After created, now in db looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GW6xQ7M4h1YSxB393bLblQ.png" /></figure><p>When building web applications in Go, establishing a connection to a PostgreSQL database is a common requirement. In this guide, we’ll walk through the process of setting up a database connection using the PostgreSQL driver in Go.</p><p><em>database.go</em></p><p><strong>Setting Up Database Connection in Go using PostgreSQL Driver</strong></p><pre>package main<br><br>import (<br> &quot;database/sql&quot;<br> _ &quot;github.com/lib/pq&quot;<br>)<br><br>func NewDB(dbDriver string, dbSource string) *sql.DB {<br> db, err := sql.Open(dbDriver, dbSource)<br><br> if err != nil {<br>  panic(err)<br> }<br><br> return db<br>}</pre><p>First, we need to import the necessary packages in our Go code. We’ll import the database/sql package, which provides the interface for working with SQL databases, and the PostgreSQL driver package, which allows Go to communicate with PostgreSQL databases.</p><p><em>service.go</em></p><p>First, let’s establish a connection to our PostgreSQL database. We’ll use the database/sql package along with the PostgreSQL driver package (github.com/lib/pq) to interact with the database.</p><pre>package main<br><br>import (<br>    &quot;database/sql&quot;<br>    &quot;net/http&quot;<br>)<br><br>type Service struct {<br>    db *sql.DB<br>}<br><br>func NewService(db *sql.DB) *Service {<br>    return &amp;Service{db: db}<br>}</pre><p>In the Service struct, we&#39;ll store the database connection, and we&#39;ll define a constructor function NewService to initialize the service with the database connection.</p><p>Next, let’s implement the CRUD operations for our API. We’ll create methods within our Service struct to handle each operation.</p><pre>func (s *Service) CreateProduct(writer http.ResponseWriter, request *http.Request) {<br>    // Implementation for creating a new product<br>}<br><br>func (s *Service) GetProducts(writer http.ResponseWriter, request *http.Request) {<br>    // Implementation for fetching all products<br>}</pre><p>In the CreateProduct method, we&#39;ll read the request body to get the product data, insert it into the database, and return the created product.</p><p>In the GetProducts method, we&#39;ll query the database to fetch all products and return them as a response.</p><p><strong>Designing the Router</strong></p><p><em>router.go</em></p><p>Our router will be represented by a struct containing a map of routes, where each route corresponds to a specific HTTP method. We’ll define methods to add routes and handle incoming HTTP requests.</p><pre>package main<br><br>import (<br>    &quot;database/sql&quot;<br>    &quot;net/http&quot;<br>)<br><br>type router struct {<br>    routes map[string]map[string]http.HandlerFunc<br>}<br><br>func NewRouter(db *sql.DB) *router {<br>    router := &amp;router{<br>        routes: make(map[string]map[string]http.HandlerFunc),<br>    }<br><br>    service := NewService(db)<br><br>    router.addRoute(&quot;POST&quot;, &quot;/products&quot;, service.CreateProduct)<br>    router.addRoute(&quot;GET&quot;, &quot;/products&quot;, service.GetProducts)<br><br>    return router<br>}</pre><p>In the NewRouter function, we initialize a new router instance and associate routes with their corresponding HTTP methods. We&#39;ll use this function to set up our router when initializing our API service.</p><p>Implementing HTTP Handlers</p><pre>func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {<br>    if handlers, ok := r.routes[req.URL.Path]; ok {<br>        if handler, methodExists := handlers[req.Method]; methodExists {<br>            handler(w, req)<br>            return<br>        }<br>    }<br>    http.NotFound(w, req)<br>}</pre><p>In the addRoute method, we simply add a new route to our router&#39;s map of routes, associating it with the specified HTTP method.</p><pre>func (r *router) addRoute(method, path string, handler http.HandlerFunc) {<br>    if r.routes[path] == nil {<br>        r.routes[path] = make(map[string]http.HandlerFunc)<br>    }<br>    r.routes[path][method] = handler<br>}</pre><p><em>main.go</em></p><p>First, we’ll initialize a connection to our PostgreSQL database using the NewDB function. We&#39;ll pass the database driver and connection string as arguments to this function.</p><pre>db := NewDB(&quot;postgres&quot;, &quot;user=root dbname=tutorial password=root sslmode=disable&quot;)</pre><p>Next, we’ll configure our HTTP router using the NewRouter function. We&#39;ll pass the database connection (db) to this function to integrate it with our router.</p><pre>router := NewRouter(db)</pre><p>Now that we have our database connection and router set up, we can start the HTTP server. We’ll configure the server to listen on port 8080 and use our router as the request handler. Finally, we’ll start the HTTP server by calling the ListenAndServe method on our http.Server instance.</p><pre>server := http.Server{<br>  Addr:    &quot;:8080&quot;,<br>  Handler: router,<br> }<br><br> fmt.Println(&quot;listening to port 8080...&quot;)<br> err := server.ListenAndServe()<br> if err != nil {<br>  panic(err)<br> }</pre><p>This starts the HTTP server and listens for incoming requests on port 8080. If any errors occur during server startup, we&#39;ll panic and print the error message.</p><p><strong>Testing the API using Postman</strong></p><p>Awesome! Now, for the final step, let’s create products using the REST API we’ve constructed with the <strong>POST</strong> method at <em>/products</em>. Here’s the JSON data for the request body:</p><pre>{<br>    &quot;name&quot;:&quot;indomie goreng&quot;,<br>    &quot;price&quot;:3000,<br>    &quot;stock&quot;:10<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*iF22UbDixLaj6yv6bEF2HA.png" /></figure><p>To retrieve all products, simply use the GET method at /products. Voilà! You’ll receive all the product data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ctPILPz3sL_etnsph7F3Eg.png" /></figure><p><strong>Conclusion</strong></p><p>In conclusion, we’ve demonstrated how to create a RESTful API service entirely without relying on any frameworks or libraries. Leveraging the simplicity and speed of development offered by native Go, we’ve achieved excellent results. This journey showcases the power and versatility of Go in crafting efficient and scalable web services. With Go, the possibilities are endless, and the development process remains both straightforward and efficient.</p><p>Full example code <a href="https://github.com/benebobaa/simple-native-crud"><em>https://github.com/benebobaa/simple-native-crud</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=920cd6eab3be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>