<?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 Muhammad Arifin on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Arifin on Medium]]></description>
        <link>https://medium.com/@muhammadarifineffendi?source=rss-9365998fc0df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hbTufwvVLKucecpoY7SaaQ.jpeg</url>
            <title>Stories by Muhammad Arifin on Medium</title>
            <link>https://medium.com/@muhammadarifineffendi?source=rss-9365998fc0df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 17:46:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammadarifineffendi/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[Build an AI Speech to Text App with OpenAI Whisper & Next.js App Router — Part 2]]></title>
            <link>https://medium.com/@muhammadarifineffendi/build-an-ai-speech-to-text-app-with-openai-whisper-next-js-app-router-part-2-992f49700472?source=rss-9365998fc0df------2</link>
            <guid isPermaLink="false">https://medium.com/p/992f49700472</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Muhammad Arifin]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 16:03:10 GMT</pubDate>
            <atom:updated>2025-04-24T16:03:10.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RXD8ioR4PQKeDMm_LzIDA.png" /><figcaption>AI Speech-to-Text/Transcriber Application Flow</figcaption></figure><h3>Build an AI Speech to Text App with OpenAI Whisper &amp; Next.js App Router — Part 2</h3><p>Welcome to Part-2 of building an AI Speech-to-Text application with OpenAI Whisper API and Next.js App Router!</p><p>On <a href="https://medium.com/@muhammadarifineffendi/build-an-ai-speech-to-text-app-with-openai-whisper-next-js-part-1-db6546e26fb0">Part-1</a>, we’ve covered several things including:</p><ul><li>main motivation of the project</li><li>application flow, requirements, flowchart diagrams, and screens</li><li>and, the implementation for AudioRecorder component in <strong>Step 1 </strong>and TranscriptionDisplay on <strong>Step 2.</strong></li></ul><p>Now in this Part-2, we will build the rest of the things and make the application finally working. Thanks for sticking by!</p><p>In case you forget, here’s the sketch of the screens we are building in this simple app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hea6cMvMlkpbcd18FB40iw.png" /><figcaption>AI Transcriber Screens</figcaption></figure><h3>Review what we need to build</h3><p>Let’s review what we are going to build in this article, we’ve got several things to cover including:</p><ul><li>the main component to handle audio transcription &amp; passing the transcription data to the TranscriptionDisplay component (<strong>Step 3</strong>)</li><li>custom transcription service with OpenAI SDK (<strong>Step 4</strong>), and</li><li>a Next.js server action to generate voice transcription with the custom transcription service (<strong>Step 5</strong>).</li></ul><p>Alright, let’s get started right away!</p><h3>Step 3: Implementing Main Page</h3><h4>Data &amp; Handlers</h4><p>For the main page, we will handle several application states:</p><ul><li>transcription text (transcription)</li><li>transcription generation progress ( isTranscribing), and</li><li>error generating transcription (isError)</li></ul><p>We will also need to implement two function handlers for:</p><ul><li>getting the audio from the AudioRecorder component when recording is stopped and generate transcription after that, and</li><li>a callback function for handling retry recording</li></ul><h4>Main Page Implementation</h4><p>Here’s how the entire logics and JSX looks like. It’s quite self-explanatory code, so I didn’t put any comments on each codes. Try to understand it by yourself or use ChatGPT for it.</p><pre>&#39;use client&#39;;<br><br>import { useState } from &#39;react&#39;;<br>import { AudioRecorder } from &#39;@/components/audio-recorder&#39;;<br>import { TranscriptionDisplay } from &#39;@/components/transcription-display&#39;;<br>import transcribeAction from &#39;@/actions/transcribe.action&#39;;<br><br>export default function Home() {<br>    const [transcription, setTranscription] = useState(&#39;&#39;);<br>    const [isTranscribing, setIsTranscribing] = useState(false);<br>    const [error, setError] = useState&lt;string&gt;();<br><br>    const handleRecordingComplete = async (audioBlob: Blob) =&gt; {<br>        setIsTranscribing(true);<br>        setError(undefined);<br><br>        try {<br>            // THIS IS WHERE OPENAI COME INTO PLAY<br>            const result = await transcribeAction(audioBlob);<br>            if (result.error) {<br>                setError(result.error);<br>            } else {<br>                setTranscription(result.text);<br>            }<br>        } catch (err) {<br>            setError(err instanceof Error ? err.message : &#39;Failed to transcribe audio&#39;);<br>        } finally {<br>            setIsTranscribing(false);<br>        }<br>    };<br><br>    const onRetryRecording = () =&gt; {<br>        setTranscription(&#39;&#39;);<br>        setError(undefined);<br>    };<br><br>    return (<br>        &lt;div className=&quot;flex flex-col items-center justify-center min-h-screen bg-gradient-to-b from-indigo-50 to-white p-8&quot;&gt;<br>            &lt;div className=&quot;w-full max-w-2xl bg-white rounded-xl shadow-lg p-8 space-y-8&quot;&gt;<br>                &lt;h1 className=&quot;text-4xl font-bold text-center text-indigo-900&quot;&gt;AI Transcribe&lt;/h1&gt;<br><br>                &lt;AudioRecorder<br>                    onRecordingComplete={handleRecordingComplete}<br>                    onRetryRecording={onRetryRecording}<br>                /&gt;<br><br>                &lt;TranscriptionDisplay<br>                    text={transcription}<br>                    isLoading={isTranscribing}<br>                    error={error}<br>                /&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p>In the implementation above, you can see that we have transcribeAudio function for transcribing the recorded audio. This is where we will call OpenAI whisper API. We&#39;ll implement it in the next section.</p><p>Alright, I hope you still have lots of energy left. If not, sip your coffee and some snacks. Relax, then let’s continue building!</p><h3>Step 4: Implementing OpenAI Service</h3><p>For the audio transcription, we will use OpenAI whisper API and use the official openai SDK from the OpenAI team. There are two things that we need:</p><ul><li>an openai SDK instantiation with valid API key, and</li><li>a custom transcribe service that will handles audio transcription</li></ul><h4>OpenAI SDK</h4><p>To use the OpenAI SDK, do the following things:</p><ol><li>Create .env file. Then add OPENAI_API_KEY=your-open-ai-api-key as an environment variable</li><li>Create a libs/ folder under src/</li><li>Create openai.ts file under libs</li></ol><p>Then, inside the file write the following code:</p><pre>import OpenAI from &#39;openai&#39;;<br><br>const openai = new OpenAI({<br>    apiKey: process.env.OPENAI_API_KEY,<br>});<br><br>export default openai;</pre><p>Alright, now we’re ready for the next step.</p><h4>Creating Transcribe Audio Service</h4><p>Before creating the transcribe function, let’s add a TranscriptionResult data model. Follow the following steps:</p><ol><li>Create models/ folder under src/</li><li>Next, create transcription.model.ts file</li><li>Inside the file, paste the code below.</li></ol><pre>export type TranscriptionResult = {<br>    text: string;<br>    error?: string;<br>};</pre><p>You might be confused with so many folders and files. Worry not, I’m just guiding you to implement things with Clean Architecture approach. So for now, just follow along.</p><p>Next, create a services/ folder under src/. Inside the services/ folder, let&#39;s implement the transcription service now. Here&#39;s how it looks like</p><pre>import openai from &#39;@/libs/openai&#39;;<br>import { TranscriptionResult } from &#39;@/models/transcription.model&#39;;<br><br>export async function transcribeAudio(audioBlob: Blob): Promise&lt;TranscriptionResult&gt; {<br>    try {<br>        const arrayBuffer = await audioBlob.arrayBuffer();<br>        const file = new File([arrayBuffer], &#39;audio.webm&#39;, { type: &#39;audio/webm&#39; });<br><br>        console.log(&#39;in progress transcribing...&#39;);<br>        const transcription = await openai.audio.transcriptions.create({<br>            file,<br>            model: &#39;whisper-1&#39;,<br>            language: &#39;en&#39;,<br>            response_format: &#39;text&#39;,<br>            temperature: 0,<br>        });<br>        console.log(&#39;finished transcribing&#39;);<br><br>        return {<br>            text: transcription,<br>        };<br>    } catch (error) {<br>        console.error(&#39;Transcription error:&#39;, error);<br>        return {<br>            text: &#39;&#39;,<br>            error: error instanceof Error ? error.message : &#39;Failed to transcribe audio&#39;,<br>        };<br>    }<br>}</pre><p>Great job! Now, let’s move on with the last implementation. We need to implement a Next.js server action to link our UI with transcribeAudio service that will hit OpenAI API for transcription generation.</p><h3>Step 5: Implementing Server Action for Audio Transcription</h3><p>For the server action, first create a transcribe.action.ts file inside the app folder. In this file, copy paste the following codes.</p><pre>&#39;use server&#39;;<br><br>import { TranscriptionResult } from &#39;@/models/transcription.model&#39;;<br>import { transcribeAudio } from &#39;@/services/transcription/transcription.service&#39;;<br><br>export default async function transcribeAction(audio: Blob): Promise&lt;TranscriptionResult&gt; {<br>    try {<br>        const { text: transcription } = await transcribeAudio(audio);<br><br>        return {<br>            text: transcription,<br>        };<br>    } catch (error) {<br>        console.error(&#39;Transcription error:&#39;, error);<br>        return {<br>            text: &#39;&#39;,<br>            error: error instanceof Error ? error.message : &#39;Failed to transcribe audio&#39;,<br>        };<br>    }<br>}</pre><p>It is a Next.js server action that will run the transcribeAudio service with OpenAI. With server action, we can be sure that our code will run on server and the API Key will not leak into browser.</p><p>Other than server action, you can also implement the same thing with Next.js API route. But for me, server action is a more compact and concise way to implement API-related logics. No need to define route file, route handler, and those REST API things.</p><h3>We’re Done!</h3><p>Alright, now we are finally done! Save everything, then on your terminal run the following command:</p><pre>npm run dev</pre><p>It everything goes well, you should be able to start recording, stop recording, and get audio transcription from OpenAI.</p><p>If you have problems, you can check out the final code in my <a href="https://github.com/ifindev/ai-transcribe/tree/initial-version">GitHub repository</a>. Clone the code, and play around with it.</p><p>Anyway, this is just a basic things. At a first glance, it looks simple! But upon building things, we found out that there are quite a lot of moving parts in the app.</p><p>That’s why on my previous article, I explain that you should just build simple things if you got no idea what to build. Pick an OpenAI API, then build something silly and stupidly simple. You’ll learn a lot with it.</p><h3>Improvement Ideas — Do it Yourself!</h3><p>If you want, try to add as many features as you want. Some ideas you can try out:</p><ul><li>Format transcription with OpenAI gpt-4o-mini before showing it to user. See my current <a href="https://github.com/ifindev/ai-transcribe">GitHub Repository </a>for this project for inspiration on how to implement it.</li><li>Upload audio file to Cloudflare R2, then store the uploaded URL and transcriptions in a database.</li><li>Generate a summary and insights from the recording with gpt-4o-mini</li><li>etc</li></ul><p>The sky is really the limit!</p><p>Checkout my <a href="https://github.com/ifindev/ai-transcribe">GitHub repository</a> for the things I’m currently working on the project.</p><p>Thanks for following along!</p><p>Btw, I open-sourced this project’s codes. If you are curious of how I implemented things, as mentioned before, you can visit the project’s <a href="https://github.com/ifindev/ai-transcribe">GitHub Repository</a>. Clone it, and play around with it!</p><p>I’m adding lots of cool things into it — so, you will definitely learn tons of things by going through all the codes.</p><p>Good luck and keep building!</p><blockquote><em>P.S: Please leave and share this article as much as possible, it would help me grow more and write down detailed tutorials like this. Thanks!</em></blockquote><blockquote>Another P.S:<br>You can read my other articles too:<br>- <a href="https://medium.com/@muhammadarifineffendi/how-to-get-openai-api-key-for-your-10k-month-saas-app-bd196eb509bf">Getting an OpenAI API Key</a><br>- <a href="https://medium.com/@muhammadarifineffendi/build-an-ai-speech-to-text-app-with-openai-whisper-next-js-part-1-db6546e26fb0">Build an AI Speech to Text App with OpenAI Whisper &amp; Next.js App Router — Part 1</a><br>- <a href="https://medium.com/@muhammadarifineffendi/not-sure-what-saas-to-build-try-tinkering-with-the-basics-d176a92faf48">Not Sure What SaaS to Build? Try Tinkering with the Basics!</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=992f49700472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an AI Speech to Text App with OpenAI Whisper & Next.js — Part 1]]></title>
            <link>https://medium.com/@muhammadarifineffendi/build-an-ai-speech-to-text-app-with-openai-whisper-next-js-part-1-db6546e26fb0?source=rss-9365998fc0df------2</link>
            <guid isPermaLink="false">https://medium.com/p/db6546e26fb0</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Muhammad Arifin]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 13:17:23 GMT</pubDate>
            <atom:updated>2025-04-24T16:06:40.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*wRu-AqUdmFaVHnnfyqgskQ.png" /><figcaption>AI Speech-to-Text/Transcriber Application Flow</figcaption></figure><h3><strong>Build an AI Speech to Text App with OpenAI Whisper &amp; Next.js App Router — Part 1</strong></h3><p><strong>This is two-series articles:</strong></p><ul><li><a href="https://medium.com/@muhammadarifineffendi/build-an-ai-speech-to-text-app-with-openai-whisper-next-js-part-1-db6546e26fb0">Part — 1: THIS PAGE</a></li><li><a href="https://medium.com/@muhammadarifineffendi/build-an-ai-speech-to-text-app-with-openai-whisper-next-js-app-router-part-2-992f49700472">Part — 2</a></li></ul><h3>Why building an AI Speech to Text app?</h3><p>Last week, I got curious on building a simple AI Speech to Text app or an AI Voice Transcriber with OpenAI Whisper API. Since I am really familiar with Next.js, I decided to build the app with it.</p><p>I thought it would be hard to do, since most YouTube tutorials took about an hour or so. But quite unexpectedly, I got everything working in just under 10 minutes! Super crazy I must say.</p><p>So, in this article, I will be sharing about how to do it the quickest and the easiest way.</p><p>Prepare your coffee, and let’s get started!</p><p>Below is the demo video of the first version of the App I’ve built. Right now, it looks completely different. But the functionalities remain the same. Take a look at it first to get a feel of what we’re going to be building in this tutorial.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0_nBOfQUv9s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0_nBOfQUv9s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0_nBOfQUv9s%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e214eace407386ed938269c552d68a1c/href">https://medium.com/media/e214eace407386ed938269c552d68a1c/href</a></iframe><h3>First step — get your OpenAI API key</h3><p>For this project, you need to have a valid OpenAI API Key. If you don’t have one yet, you can check my other article about <a href="https://medium.com/p/bd196eb509bf">Creating an OpenAI API Key</a>.</p><p>If you got one already, then you’re good to go.</p><h3>Application Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhE8rP_Lnd4SNutmv8z9WQ.png" /><figcaption>AI Transcriber Application Flow</figcaption></figure><p>For this project, we will go with the simplest approach as shown in the above image. There are <strong>three core features</strong> that we will be building:</p><ol><li>record audio with user’s microphone in chunks</li><li>generate text transcription from audio with OpenAI whisper Speech-To-Text (STT) model</li><li>show the final transcription in the UI</li></ol><p>That’s it. No fancy features, no fancy UI, just a small enough for an MVP.</p><p>Next, let’s prepare our Next.js application and other development dependencies.</p><h3>Next.js &amp; Dependencies Setup</h3><h4>Setup Next.js</h4><p>To get started, first you need to setup a fresh Next.js application. We will be using pnpm as our package manager to install things.</p><p>Now, choose a folder where you want to store the project, then run the following command on your terminal:</p><pre>pnpm create next-app@latest</pre><p>You will get multiple questions on your terminal. Just enter your app name, for example <em>“ai-transcriber”</em>, then just click “Enter” until you’re finished with all the questions.</p><p>After the initial setup is finished, open up the project with your code editor. If you have VS Code installed, you can run this command on terminal:</p><pre>code your-app-name</pre><p>Then, install lucide-react for an icon library with this command:</p><pre>pnpm install lucide-react</pre><h4>Install OpenAI SDK</h4><p>Next, we will need the official openai SDK to connect with OpenAI. Make sure your terminal is on the current project, then run the following command on your editor terminal:</p><pre>pnpm install openai</pre><p>Wait a minute until installation is finished, then you are good to go!</p><h3>Take a deep breath first 😄</h3><p>Great job making it this far! You’re doing awesome!</p><p>Take a deep breath, sip your coffee. We’ll have a long journey awaiting us. Now, let’s get on with the actual building, shall we?</p><h3>Application Flow &amp; Screens</h3><p>Before we code, it’s always a good idea to first understand the complete application flow of our app. This will help us to plan out:</p><ul><li>how our codes should be implemented</li><li>what kind of screens/UIs do we need</li><li>how do each UI components interact with each other</li></ul><h4>AI Transcriber Application Flow</h4><p>Based on the features we’ve discussed previously, this is the simplest flow for our app:</p><ol><li>user opens up the app, click button to record audio</li><li>app start recording the audio, while showing recording indicator and stop button to user</li><li>user clicks stop recording button, then two things appear: <br>- audio preview and button to re-record audio<br>- a loading showing transcription is being processed</li><li>when transcription loading is finished the final transcription is shown to the user</li><li>if user click Record Again button, then we’ll show the record audio button again.</li></ol><p>This flow can be easily understood with a simple flowchart. You can see the flowchart diagram below capturing all those previous points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*To0d2rsdjFFtnk-qHHc90g.png" /><figcaption>AI Transcriber Flowchart Diagram</figcaption></figure><h4>Application Screens</h4><p>With the previous flowchart, we now know that we need four basic UI screens for:</p><ul><li>Start a recording</li><li>Recording in progress</li><li>Finished recording &amp; generating transcription</li><li>Finished transcription generation</li></ul><p>This is a sketch of how the screens will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCnG_ZNZP4op2ZuxYbQz4A.png" /><figcaption>AI Transcriber Screens</figcaption></figure><p>Now, let’s start implementing things!</p><h3>Step 1: Handle Recording Process</h3><p>Not like other tutorials that just focuses on code, I want to help you understand things beyond code. Think through the problem first, breakdown all the details, plan your implementation, then code with the created plan.</p><p>For this step, we will plan out the AudioRecorder component for audio recording, and then implement it based on the plan.</p><h4>Designing the AudioRecorder Component</h4><p>The AudioRecorder component will responsible for several things:</p><ul><li>Handle start recording &amp; getting audio data in small chunks (<em>note: we’ll talk more about chunks later</em>).</li><li>Handle stop recording, generate an audio URL for recording preview, and trigger a callback function onRecordingComplete to pass the recorded audio for transcription.</li><li>Handle retry recording when user click Record Again button and trigger an onRetryRecording callback function to notify parent component when retry recording is requested.</li></ul><p>Alright, let’s write down some codes now!</p><h4>Building the AudioRecorder Logics</h4><p>First, let’s start building the AudioRecorder UI component. We&#39;ll use TailwindCSS that is pre-configured with a Next.js installation. Follow this steps:</p><ol><li>Create a components folder under src/ directory.</li><li>Then, create audio-recorder.tsx file inside the components directory.</li><li>Inside, create the AudioRecorder component.</li></ol><p>Let’s start breaking down the component piece by piece. We will start with the state, data, and function handlers following the previous plan.</p><p>First, let’s define the state, data, and function handlers that we will need:</p><pre>import { useState, useRef } from &#39;react&#39;;<br><br>type AudioRecorderProps = {<br>    onRetryRecording: () =&gt; void;<br>    onRecordingComplete: (audioBlob: Blob) =&gt; void;<br>}<br><br>export function AudioRecorder({ <br>  onRetryRecording,<br>  onRecordingComplete, <br>}: AudioRecorderProps) {<br>    const [isRecording, setIsRecording] = useState(false);<br>    const [recordedAudioUrl, setRecordedAudioUrl] = useState&lt;string | null&gt;(null);<br>    <br>    const audioChunksRef = useRef&lt;Blob[]&gt;([]);<br>    const mediaRecorderRef = useRef&lt;MediaRecorder | null&gt;(null);<br><br>    const handleStartRecording = async () =&gt; {<br>    };<br><br>    const handleStopRecording = () =&gt; {<br>    };<br><br>    const handleRecordAgain = () =&gt; {<br>    };<br><br>    return (<br>        &lt;div&gt;<br>            Audio Recorder<br>        &lt;/div&gt;<br>    );<br>}</pre><p>isRecording: boolean</p><ul><li>Tracks whether recording is currently in progress.</li><li>Used to conditionally toggle UI and logic (e.g., show “Stop” vs. “Start”).</li></ul><p>recordedAudioUrl: string | null</p><ul><li>Stores the URL for the recorded audio blob.</li><li>Used to enable audio playback after recording is stopped.</li></ul><p>audioChunksRef: Blob[]</p><ul><li>Stores all audio chunks collected during recording.</li><li>These chunks are combined into a single Blob once recording stops.</li><li>We use ref to avoid re-renders.</li></ul><p>mediaRecorderRef: MediaRecorder | null</p><ul><li>Holds the MediaRecorder instance used to capture audio from the device microphone.</li><li>Necessary to start/stop recording and manage the audio stream.</li><li>We use ref to avoid re-renders.</li></ul><p>Next, we need to implement the three function handlers that were defined before.</p><h4>Implementing AudioRecorder Handlers</h4><p>Here’s how the function handlers for handleStartRecording , handleStopRecording, and hanleRecordAgain are implemented</p><pre>import { useState, useRef } from &#39;react&#39;;<br><br>type AudioRecorderProps = {<br>    onRetryRecording: () =&gt; void;<br>    onRecordingComplete: (audioBlob: Blob) =&gt; void;<br>}<br><br>export function AudioRecorder({ <br>  onRetryRecording,<br>  onRecordingComplete, <br>}: AudioRecorderProps) {<br>    const [isRecording, setIsRecording] = useState(false);<br>    const [recordedAudioUrl, setRecordedAudioUrl] = useState&lt;string | null&gt;(null);<br>    <br>    const audioChunksRef = useRef&lt;Blob[]&gt;([]);<br>    const mediaRecorderRef = useRef&lt;MediaRecorder | null&gt;(null);<br><br>    const handleStartRecording = async () =&gt; {<br>      // Clear any previously recorded audio URL from state<br>      setRecordedAudioUrl(null);<br>  <br>      // Reset the array that stores audio chunks<br>      audioChunksRef.current = [];<br>  <br>      // Request access to the user&#39;s microphone<br>      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });<br>  <br>      // Create a new MediaRecorder instance using the audio stream<br>      const mediaRecorder = new MediaRecorder(stream);<br>  <br>      // Save the recorder instance to the ref so it can be accessed later<br>      mediaRecorderRef.current = mediaRecorder;<br>  <br>      // When audio data is available (every 500ms), store it in the chunks array<br>      mediaRecorder.addEventListener(&#39;dataavailable&#39;, (event) =&gt; {<br>          if (event.data.size &gt; 0) {<br>              audioChunksRef.current.push(event.data);<br>          }<br>      });<br>  <br>      // When recording stops, combine chunks and trigger callback<br>      mediaRecorder.addEventListener(&#39;stop&#39;, () =&gt; {<br>          // Combine the audio chunks into a single Blob<br>          const audioBlob = new Blob(audioChunksRef.current, { type: &#39;audio/webm&#39; });<br>  <br>          // Create a URL from the Blob for audio playback<br>          const audioUrl = URL.createObjectURL(audioBlob);<br>  <br>          // Save the playback URL in state<br>          setRecordedAudioUrl(audioUrl);<br>  <br>          // Notify parent component with the final audio Blob<br>          onRecordingComplete(audioBlob);<br>      });<br>  <br>      // Start recording and collect audio chunks every 500ms<br>      mediaRecorder.start(500);<br>  <br>      // Set recording state to true<br>      setIsRecording(true);<br>    };<br>    <br>    const handleStopRecording = () =&gt; {<br>      // If recording is active<br>      if (mediaRecorderRef.current) {<br>          // Stop the media recorder (this triggers the &#39;stop&#39; event)<br>          mediaRecorderRef.current.stop();<br>  <br>          // Stop all tracks from the media stream to release the microphone<br>          mediaRecorderRef.current.stream.getTracks().forEach((track) =&gt; track.stop());<br>  <br>          // Update recording state to false<br>          setIsRecording(false);<br>      }<br>    };<br>    <br>    const handleRecordAgain = () =&gt; {<br>      // Clear the previously recorded audio URL<br>      setRecordedAudioUrl(null);<br>  <br>      // Reset the stored audio chunks<br>      audioChunksRef.current = [];<br>  <br>      // Set recording state to false (just in case)<br>      setIsRecording(false);<br>  <br>      // Notify parent component that recording is being restarted<br>      onRetryRecording();<br>    };<br><br>    return (<br>        &lt;div&gt;<br>            Audio Recorder<br>        &lt;/div&gt;<br>    );<br>}</pre><h4>Implementing AudioRecorder UI</h4><p>Now, let’s implement the AudioRecorder UI. It should cover case for:</p><ul><li>Start a recording</li><li>Recording in progress</li><li>Audio playback &amp; retry record</li></ul><p>Here’s how the component will looks like now:</p><pre>import { Mic, StopCircle, RotateCcw } from &#39;lucide-react&#39;;<br>import { useState, useRef } from &#39;react&#39;;<br><br>interface AudioRecorderProps {<br>    onRecordingComplete: (audioBlob: Blob) =&gt; void;<br>    onRetryRecording: () =&gt; void;<br>}<br><br>export function AudioRecorder({ onRecordingComplete, onRetryRecording }: AudioRecorderProps) {<br>    <br>    // Same codes as the previous section for logics<br><br>    return (<br>        &lt;div className=&quot;flex flex-col items-center gap-4&quot;&gt;<br>            {/* Show recording progress when in-progress recording*/}<br>            {isRecording &amp;&amp; (<br>                &lt;div className=&quot;flex items-center space-x-1&quot;&gt;<br>                    &lt;div className=&quot;w-3 h-3 bg-red-500 rounded-full animate-pulse&quot; /&gt;<br>                    &lt;span className=&quot;text-sm text-gray-600&quot;&gt;Recording...&lt;/span&gt;<br>                &lt;/div&gt;<br>            )}<br>            <br>            {/* <br>             - Show Start/Stop Recording button when no audio is recorded  <br>             - handleStartRecording when button is clicked when not recording<br>             - handleStopRecording when button is clicked when recording<br>            */}<br>            {!recordedAudioUrl &amp;&amp; (<br>                &lt;button<br>                    onClick={isRecording ? handleStopRecording : handleStartRecording}<br>                    className={`flex items-center gap-2 px-5 py-2 rounded-lg font-semibold text-white ${<br>                        isRecording<br>                            ? &#39;bg-red-600 hover:bg-red-700&#39;<br>                            : &#39;bg-blue-600 hover:bg-blue-700&#39;<br>                    }`}<br>                &gt;<br>                    {isRecording ? (<br>                        &lt;&gt;<br>                            &lt;StopCircle className=&quot;w-4 h-4&quot; /&gt;<br>                            Stop Recording<br>                        &lt;/&gt;<br>                    ) : (<br>                        &lt;&gt;<br>                            &lt;Mic className=&quot;w-4 h-4&quot; /&gt;<br>                            Start Recording<br>                        &lt;/&gt;<br>                    )}<br>                &lt;/button&gt;<br>            )}<br><br>            {/* <br>             - Show when there is a recorded audio<br>             - Show recorded audio and Record Again button when audio is recorded<br>             - handleRecordAgain when button is clicked<br>            */}<br>            {recordedAudioUrl &amp;&amp; (<br>                &lt;&gt;<br>                    &lt;div className=&quot;flex items-center justify-center gap-4&quot;&gt;<br>                        &lt;audio src={recordedAudioUrl} controls /&gt;<br><br>                        &lt;button<br>                            className=&quot;bg-blue-500 text-white font-semibold p-2 rounded-md flex items-center gap-2&quot;<br>                            onClick={handleRecordAgain}<br>                        &gt;<br>                            &lt;RotateCcw className=&quot;w-4 h-4&quot; /&gt;<br>                            Record Again<br>                        &lt;/button&gt;<br>                    &lt;/div&gt;<br>                    &lt;p className=&quot;text-gray-600&quot;&gt;<br>                        {!document.createElement(&#39;audio&#39;).canPlayType(&#39;audio/webm&#39;) &amp;&amp;<br>                            &#39;Your browser does not support the audio element.&#39;}<br>                    &lt;/p&gt;<br>                &lt;/&gt;<br>            )}<br>        &lt;/div&gt;<br>    );<br>}</pre><p>Now with that, we’re done with the AudioRecorder! What a journey it has been.</p><p>Next, let’s implement the component for showing the transcription. We will call it TranscriptionDisplay component.</p><h3>Step 2: Implementing Transcription Display</h3><p>The TranscriptionDisplay component is simpler compared to the AudioRecorder component. It just need to display loading state, error state, and the final transcription.</p><p>Here’s how the component is implemented:</p><pre>import { Loader2 } from &#39;lucide-react&#39;<br><br>type TranscriptionDisplayProps = {<br>    text: string;<br>    isLoading: boolean;<br>    error?: string;<br>}<br>export function TranscriptionDisplay({ <br>  text, <br>  isLoading, <br>  error <br>}: TranscriptionDisplayProps) {<br>    if (isLoading) {<br>        return (<br>            &lt;div className=&quot;flex items-center justify-center gap-2 text-gray-600&quot;&gt;<br>                &lt;Loader2 className=&quot;w-4 h-4 animate-spin&quot; /&gt;<br>                &lt;span&gt;Transcribing...&lt;/span&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>    if (error) {<br>        return (<br>            &lt;div className=&quot;text-red-500 text-center&quot;&gt;<br>                &lt;p&gt;Error: {error}&lt;/p&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>    if (!text) {<br>        return null;<br>    }<br>    return (<br>        &lt;div className=&quot;bg-gray-50 p-4 rounded-lg&quot;&gt;<br>            &lt;h3 className=&quot;text-lg font-semibold mb-2&quot;&gt;Transcription&lt;/h3&gt;<br>            &lt;p className=&quot;text-gray-700 whitespace-pre-wrap&quot;&gt;{text}&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p>Next, we need to combine the AudioRecorder and the TranscriptionDisplay components in the main page.</p><p>Since this has become too long, let’s continue on the second part of this article. Especially, since we still have quite a lot to cover. Buttt, please don’t lose heart!</p><p>Don’t forget to catch your breath. Releax for a bit. You’re doing great! You can do it! Let’s finish this thing!!!</p><p>Alright, see you on the<a href="https://medium.com/@muhammadarifineffendi/build-an-ai-speech-to-text-app-with-openai-whisper-next-js-app-router-part-2-992f49700472"> Next Article!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db6546e26fb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get OpenAI API Key for your $10K/month SaaS App]]></title>
            <link>https://medium.com/@muhammadarifineffendi/how-to-get-openai-api-key-for-your-10k-month-saas-app-bd196eb509bf?source=rss-9365998fc0df------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd196eb509bf</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Muhammad Arifin]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 15:31:15 GMT</pubDate>
            <atom:updated>2025-04-24T14:34:04.117Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZGuOTsuuI3EQ_EskKnQxw.png" /><figcaption>OpenAI Developer Platform</figcaption></figure><p>If you want to build the next amazing ChatGPT wrapper app, then one thing that you need to have is the <strong>OpenAI API Key</strong>.</p><p>With it, you can do lots of things and build a cool ChatGPT wrapper SaaS that might make you $<strong>10k/month revenue</strong>! Crazy, right?</p><p>The question is, how do you get it?</p><p>Well, if you are asking that question, then this article is for you. Keep reading!</p><h3>Step 1: Setup Billing Account</h3><p>Before you can get your API key, you need to register to OpenAI developer platform and add your credit card information detail for payment.</p><p>There are four things you need to do for it:</p><ul><li><strong>Register and account in </strong><a href="https://platform.openai.com/docs/overview"><strong>OpenAI developer platform</strong></a><strong>.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZGuOTsuuI3EQ_EskKnQxw.png" /><figcaption>OpenAI Developer Platform</figcaption></figure><ul><li>Then, go to the <a href="https://platform.openai.com/settings/organization/billing/overview">billing page</a> (<em>note: you need to register to be able to access this page</em>). After that, click <strong>“Add payment method”</strong> button to register your credit card information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTpYjYQXyhNoBIIJcBEZIQ.png" /><figcaption>Add payment methods</figcaption></figure><ul><li>Click <strong>“Add to credit balance”</strong> button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXBFtZ7kwdPBApaDBgXZFQ.png" /><figcaption>Adding credit balance</figcaption></figure><ul><li>Add a credit balance minimum $5 to your OpenAI or use your credit card for paying the API usage. Don’t worry, it’s super enough for learning process!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXmC1X2miK_dux5MhSbs4A.png" /></figure><p>Now that your billing account is set, you’re ready to get the API key.</p><h3>Step 2: Get your API Key</h3><p>Next after finished with setting up billing information, let’s get the API keys. Follow the following steps to get one:</p><ul><li>Go to the <strong>“API keys”</strong> submenu under <strong>“PROJECT”</strong> on the sidebar, then click <strong>“Create new secret key”</strong> button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dzFeGe8EvZy05pwpAlxYQ.png" /><figcaption>API keys page</figcaption></figure><ul><li>Next, a modal will appear. You need to enter the project information. You can customize what kind of access the API key can be used for by going to the <strong>“Permissions” </strong>tab.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1IVYIqmI-x0XwSQGQNF5A.png" /></figure><ul><li>Then, click the <strong>“Create secret key” </strong>button so that OpenAI generate an API key for you. Click the “Copy” button to get it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osL1ROyItNnQ0jhcs-wedQ.png" /><figcaption>Click “copy” button to save your API key</figcaption></figure><p>Now, you get your API Key!! Congrats!</p><p>Time to build that $10k/month SaaS app ideas you have.</p><p>Good luck!</p><h3>Step 3: Securing your API Key</h3><p><strong>VERY IMPORTANT:</strong></p><ul><li><strong><em>DO NOT share your API Key to anyone</em></strong>. It will costs you money, and <strong>YOU CAN GO BROKE</strong> by getting your credit card charged for OpenAI API usages.</li><li><strong>DO NOT put your API key in a client-side app </strong>like React-Vite app, Vue.js app, etc. Use a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Overview#components_of_http-based_systems">proxy server</a> for storing API keys, and expose a secure API endpoint to connect with OpenAI APIs. Or, use framework with capability to run server-side function like Next.js, Nuxt, or Laravel, etc.</li><li><strong>DELETE YOUR API KEY</strong> if you think someone might be using it. Open up the <em>Usage </em>menu on sidebar to monitor your API Key usage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g7MBeJJzKpTq4wNIWC9sNg.png" /><figcaption>Usage dashboard — always check usage to make sure you’re the only one that uses the API Key</figcaption></figure><p>Once again — BE CAREFUL WITH YOUR API KEYS!</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd196eb509bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Not Sure What SaaS to Build? Try Tinkering with the Basics!]]></title>
            <link>https://medium.com/@muhammadarifineffendi/not-sure-what-saas-to-build-try-tinkering-with-the-basics-d176a92faf48?source=rss-9365998fc0df------2</link>
            <guid isPermaLink="false">https://medium.com/p/d176a92faf48</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[saas]]></category>
            <dc:creator><![CDATA[Muhammad Arifin]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 03:16:40 GMT</pubDate>
            <atom:updated>2025-04-21T03:16:40.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0T3t-CDRSfKlZNnx2mQYkg.png" /></figure><blockquote><em>P.S: you can also read this article on my blog here </em><a href="https://ifincode.dev/blog/tinker-with-the-basic-for-saas"><em>https://ifincode.dev/blog/tinker-with-the-basic-for-saas</em></a></blockquote><p>Lately, I’ve been banging my head looking for SaaS ideas and getting envy with all those successful people making thousands or even hundreds of thousands of dollars with their SaaS.</p><p>To me, it seems like those successful people on X has great ideas, great executions, and here I am just a worthless dev couldn’t even build a simple thing.</p><p>Have you ever feel the same? Getting this huge impostor syndrome, and fear of not making it?</p><p>Or maybe feeling like you’ve been chasing multiple ideas for your SaaS, but always ended in a roadblock.</p><p>Well, me too. And in this post, I want to tell you how to get on with it and just START BUILDING WITH THE BASICS.</p><h3>Exploring the Basics — not basic programming of course</h3><p>Yep, you read that right.</p><p>Last week, I’ve come to realization that instead of keep thinking of the next $10k/month SaaS ideas, and not building anything since I fear things might be failing, I should just try to start from the basic.</p><p>By “<em>The Basic”</em>, I’m not saying you should start with basic programming like Array, for-loop, etc. But, the basic of multiple AI technologies that you can find now.</p><p>The easiest way is by checking all the available APIs from OpenAI in their <a href="https://platform.openai.com/docs/api-reference/introduction">API Docs</a>, then start building with one of the API you found there.</p><p>For example, when I’m writing this blog post, OpenAI got several Platform APIs for:</p><ul><li>Chat Completions</li><li>Streamings</li><li>Audio</li><li>Embeddings</li><li>Images</li><li>Realtime</li><li>etc</li></ul><p>Pick one thing, then explore the simplest use case you can build with it.</p><h3>Start simple — focus on backend logics, do minimum frontend works</h3><p>After you choose whatever API that you want to try, the next part is to focus on backend logic first and do minimum amount of frontend works.</p><p>I know that there are multiple platforms like Lovable, Bolt, v0, that can help you build cool looking UIs. But, JUST STOP FOR NOW.</p><p>Do not think about the UI, start thinking about the LOGIC FLOW that you want to implement. You can even do UI without any styling, just focus on building the backend functionalities first for now with the API.</p><p>If you got too many fancy UIs, you will most definitely feel overwhelmed later. Been there, done that. It’s not a good feeling.</p><p>That’s why, just build the backend function first! Make everything works with the simplest UI, then improve the UI later.</p><h3>An example — building AI transcriber app with OpenAI Whisper</h3><h4>Starting with the simplest STT idea</h4><p>As an example, last week I decided to explore about building a simplest app with OpenAI Audio API, with Whisper model.</p><p>The simplest use case I can think of is building a simple AI Transcriber App with these three core features:</p><ol><li>record audio voice from web app</li><li>transcribe the recorded audio with OpenAI Whisper speech-to-text (STT) model</li><li>show the formatted transcribed audio in the UI</li></ol><p>That’s it, no fancy real-time audio, AI agent, and all those complicated things.</p><p>With just this idea, I’ve managed to learn so much about:</p><ul><li>audio chunking</li><li>implementing speech-to-text with OpenAI whisper</li><li>implementing transcription with Next.js server action</li><li>and transcription formatting with OpenAI <em>gpt-4o-mini</em></li></ul><p>Here’s the App I’ve built</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0HPRvzYeTmWNUHWwnMxEA.png" /><figcaption>A simple AI Transcribe App with OpenAI Whisper API</figcaption></figure><h4>More ideas for AI transcription</h4><p>Then with the basic understanding of how to build with the STT API, I started to get more ideas about what to build.</p><p>Several ideas I got, for example:</p><ul><li>Real-time meeting note &amp; summarization</li><li>Tool for repurposing Podcast into written contents for LinkedIn, X, Threads, blog post, etc</li><li>Tool that take unedited video, increase sound quality, add edited list of points automatically when people explaining things in the video, etc</li><li>AI Debate Coach</li><li>Transcription as a Service for Niche Markets</li><li>etc</li></ul><p>So, just starting from the basic will give us so much confident that we can build things. Especially when we can make all the backend run as we want and doesn’t get overwhelmed by UIs, it will feels a lot better.</p><h3>What should you do now?</h3><h4>Just build the simplest stupid app without overthinking things</h4><p>Well, pick one API from OpenAI or maybe Mistral, Gemini, etc and decide on the simplest thing you can build.</p><p>For example, let’s talk about the new <a href="https://mistral.ai/news/mistral-ocr">Mistral OCR API</a>. There are a lot of things you can build with it, and lots of use cases we can use it.</p><p>But for simplicity purpose, an idea you can try is to build a simple app where you can:</p><ul><li>upload pdf only pdf file on the app</li><li>process the pdf with mistral API</li><li>then show the markdown result in the UI with the simplest styling possible</li></ul><h4>Things you will learn along the way</h4><p>When building that simple PDF tool, you might be learning new things such as:</p><ul><li>how to upload file to object storage such as AWS S3, Cloudflare R2, Supabase object storage, etc</li><li>how to use Next.js server action or API routes to connect Mistral OCR API</li><li>how to use AI SDK from Vercel, or official Mistral SDK, and other AI/LLM libraries</li><li>how to process the returned response from Mistral API, and show it on the UI of you app</li><li>etc</li></ul><p>See? Just by focusing on small and simplest stupid use case, you can learn a lot! It will also improve your confidence by just building things, without overthinking about the next $10k/month SaaS.</p><p>Just put off the SaaS for now, focus on basic things. Have fun building the basic.</p><p>After that, you can start asking ChatGPT, Grok, or other AI to give you some ideas that you can explore from the foundation you’ve build.</p><p>Some examples you can try later:</p><ul><li>How do you do PDF chunking and embeddings from the given PDF</li><li>How do you build a simple RAG app where you can ask anything about the PDF?</li><li>What if you can build quizzes from the uploaded PDF?</li><li>etc</li></ul><p>Lots of things you can build with it.</p><p>Anyway, that’s it for this post! Hope you got some inspiration, and start building without too much overthinking 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d176a92faf48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Struct Composition in Go]]></title>
            <link>https://medium.com/@muhammadarifineffendi/struct-composition-in-go-80492bd447bd?source=rss-9365998fc0df------2</link>
            <guid isPermaLink="false">https://medium.com/p/80492bd447bd</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Muhammad Arifin]]></dc:creator>
            <pubDate>Mon, 04 Jul 2022 17:11:23 GMT</pubDate>
            <atom:updated>2022-07-04T17:11:23.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*VamrqX0eIU-EmrLlXz2r_w.jpeg" /></figure><p><strong>Overview OOP in Go</strong></p><p>If you’re learning or using Go, you might notice that Go doesn’t support Class-based OOP like in other languages such as Java, C#, Javascript, PHP, and others. Instead of using class, Go provides us with struct and interface to create object and implementing composition rather than inheritance.</p><p>Since I used a lot of C on my previous job as an embedded engineer, I really love the flexibility of struct especially the way it is implemented in Go. With struct, I can define objects, compose several structs to create new object, and most importantly creating methods or receiver for each struct.</p><p><strong>Struct in Go</strong></p><p>An example of a simple Human struct can be seen below. There are four fields inside the struct which describes the common properties of a human which are name, age, height, and gender.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dc1df834f6098e3273789ff855ed8a4/href">https://medium.com/media/1dc1df834f6098e3273789ff855ed8a4/href</a></iframe><p>To create a new Human, we can define a simple factory function that will return a pointer to Human struct. This function basically will just make sure that all the fields are filled whenever a Human struct is created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e31b7a729da9d64f4443066db041df5/href">https://medium.com/media/6e31b7a729da9d64f4443066db041df5/href</a></iframe><p>After we define the Human struct and its factory function, we can add method to the object by using struct receiver. Basically these functions are the ‘methods’ of the struct object we have defined before. For the Human struct, we define SetName to modify name &amp; Introduction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7336e3d185f8e92e7ea88be69c18a06/href">https://medium.com/media/b7336e3d185f8e92e7ea88be69c18a06/href</a></iframe><p>We can now use the Human struct/object in our main function as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/897b458c24bec9c2281f7c2967c30e65/href">https://medium.com/media/897b458c24bec9c2281f7c2967c30e65/href</a></iframe><p><strong>Struct Composition</strong></p><p>Now after we are done with our Human struct, we can also define a new Employee struct as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/328d375bf3e159f15b0d1fcf429ea5bd/href">https://medium.com/media/328d375bf3e159f15b0d1fcf429ea5bd/href</a></iframe><p>If you look closely at the Employee struct above, there are fields that are belong to Human struct. This is make sense actually, since an employee is also a human. So, instead of copying and pasting, we can embed/compose the struct Human into our Employee struct.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a84e401bc316fd149939f94af6e89f4/href">https://medium.com/media/3a84e401bc316fd149939f94af6e89f4/href</a></iframe><p><strong>Has-A and </strong><strong>Is-A Relationship</strong></p><p>The above implementation looks good. But, don’t you think it’s a little bit weird?</p><p>The first time when we are defining the Human struct, we can say that a human has a name, an age, a height, and a gender. Therefore, the relationship between Human struct and the fields inside of it is a has-a relationship.</p><p>Now upon closer look into the new version of Employee struct, we can see that it wouldn’t make any sense to say that ‘Employee has a Human’. Because employee doesn’t have a human, but an employee <strong>is </strong>a human. Therefore, the relationship between Employee and Human is the is-a relationship instead of has-a .</p><p>We can implement the is-a relationship easily by embedding the Human struct as an anonymous field in the Employee struct like in the code below. Now by doing this kind of composition, we can say that <strong>Employee is a Human </strong>not has a human.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c6fad2700965919319b4ed9842e1314/href">https://medium.com/media/6c6fad2700965919319b4ed9842e1314/href</a></iframe><p><strong>Inheritance &amp; Methods Overriding</strong></p><p>Now, since Employee is a Human, the Employee struct will have access to any methods that were defined in the Human struct.</p><p>To test it, let’s first create a NewEmployee function to create a new employee object and then change our main function like in the below snippet</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c74da664a94a80ca77e4c65256124fba/href">https://medium.com/media/c74da664a94a80ca77e4c65256124fba/href</a></iframe><p>If we run the code, we can see that we have an access to the Introduction &amp; SetName function that were defined for Human struct previously. Basically, the Employee struct inherits all the fields &amp; methods from the Human struct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGXBtXjrk3a21bJwIvfc5A.png" /></figure><p>Apart from inheriting, we can also easily override the implementation of certain functions from the original struct. For our example, let’s override the Introduction method to become something like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f039a0e184cf068c9d9132fe7e89463/href">https://medium.com/media/8f039a0e184cf068c9d9132fe7e89463/href</a></iframe><p>Now if we re-run our main code, what we get is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzcWW1yXeWLssxUer8RNeA.png" /></figure><p>Awesome! How easy is that? 😆</p><p>Alrighty, that’s it for today. I hope you learn something new by reading this post. Drop a comment if you have any opinion, okay?</p><p>Thank you!</p><p>P.S: Full Code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6318fc4b6e2ed701e2e42ea15b4ec7fd/href">https://medium.com/media/6318fc4b6e2ed701e2e42ea15b4ec7fd/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80492bd447bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>