<?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 Alex on Medium]]></title>
        <description><![CDATA[Stories by Alex on Medium]]></description>
        <link>https://medium.com/@daskinnyman?source=rss-ec82708519ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*veYNLH9pW2H67PT6OoNOwg.jpeg</url>
            <title>Stories by Alex on Medium</title>
            <link>https://medium.com/@daskinnyman?source=rss-ec82708519ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:56:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daskinnyman/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[Software engineering in the era of LLM]]></title>
            <link>https://medium.com/@daskinnyman/software-engineering-in-the-era-of-llm-4e411282bb75?source=rss-ec82708519ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e411282bb75</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 10:33:39 GMT</pubDate>
            <atom:updated>2023-08-29T10:37:49.512Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>This post is also available on my blog:<br> </strong><a href="https://daskinnyman.vercel.app/"><strong>https://daskinnyman.vercel.app/</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J_PE5fygb8i6HR7t" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the fast-paced world of software engineering, adapting to the dynamic changes of the tech industry, rapid learning, and facilitating the adoption of new technologies among your team members are just a few of the challenges to face in our daily life.</p><p>A game-changer in this landscape has been the emergence of Large Language Models (LLMs) powered tools like GitHub Copilot. While these tools are lauded for enhancing productivity, concerns loom about their potential to replace human software engineers. Let’s dive into the reality and explore how, as a TypeScript developer, you can seamlessly collaborate with LLMs to amplify your development prowess.</p><h3><strong>Navigating the Era of Large Language Models</strong></h3><p>Tools powered by Large Language Models(LLM), exemplified by the likes of Copilot, have undoubtedly streamlined coding tasks for many developers. But the notion that they might render human developers obsolete is a misconception. These tools helps developers on the code-writing process, but we still needs to choose whether the solution they provided can suit the problem we are solving, Which means every piece of code generated by an LLM should be review by human for accuracy, comprehensibility, and alignment with the project’s goals.</p><p>As a software engineer entrenched in the era of Large Language Models, I admit that I feel feeling lost with these innovative tools sometimes. However, I’ve recently discovered how to harness their potential to maximize my productivity and elevate my role in this LLM-dominated landscape.</p><h3><strong>Collaborating Effectively with LLM powered tools</strong></h3><p>Working with LLM powered tools is no different than working with a real human. You can treat the LLM tools as a colleague who always sits next to you, ready to assist. Here, I present some strategies for productive collaboration, and demonstrate them with TypeScript:</p><p><strong>Document your code — Make LLM understand you code:<br></strong>Robust documentation is key to enable LLM tools to analyze your code more deeply. This not only empowers the LLM to better understand your code but also facilitates seamless integration with tools like VSCode. With GitHub Copilot and other VSCode plugin can automate JSDoc and comment generation.<br>Below screenshots are the demonstration of the documentation written in the interface, and how it can integrate with VSCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Ha16b3U8MEmmOmMGFIG_cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*GVyxg25J5x1mzAh7qZ0lmA.png" /></figure><p><strong>Craft Expressive and Consistent Naming Conventions</strong></p><p>A uniform coding style is imperative to ensure LLM-generated code aligns with the coding style you want. These are the rules to achieve this:</p><p>- When naming boolean flags, opt for positive values. Instead of isNonEmpty , use isEmpty.</p><p>- Showing the correct intent in naming. For instance, transform getUser into getUserById when the function fetches users via their IDs.</p><p>- Avoid abbreviations for better clarity.</p><h3><strong>In a Nutshell</strong></h3><p>Beyond adhering to these guidelines, encapsulate logic within functions or class methods is also important. Make sure team members can use the code you wrote easily. Thinking as you are developing a SDK or an API for other people and take more attention about how they will use code.In the era of LLM, our value as a human is to make more decision on how to make the code more “User-friendly”, and how can it boost up the productivity of the team and bring us towards success.</p><p>If you like my post, please press the like button.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Falex940131%2Fbutton&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fin%2Flike%2Falex940131&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Flikecoin-foundation.appspot.com%2Flikecoin_store_user_alex940131_main%3FGoogleAccessId%3Dlikecoin-api-public%2540likecoin-foundation.iam.gserviceaccount.com%26Expires%3D2430432000%26Signature%3DbdYzKBGHrDRBllBGJ%252F7wWuE995S40I%252B9%252Flxucpsyugs2K5DVWad4ARcRWgpYtp9btQSfKCiyzbP1ZaiGiasDsEn5TcAjZTwTweZsUdoLiuaL8v8dXheoThnp7%252FWQXWkRDChifa8INSdN6DXS18PlV%252FOOjkUyOz%252BxmnCrwYoa2E3qJ2Atey52ghkb7Eot6MFvqpHJQzufj1546jwD0uF7w6r%252Bbbse47owXDra2pwFGnZ8KPpVy5IjAaKdMJ5J5KpIRFyRZ546kEs3j3lVduqkgYuyLFQ%252FRF8dk47rHnX5xBL6bN05ILoQOCuKDtSVQoOhKtrDXXwS6rjf9adGAc6hzA%253D%253D%2607970c2&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="360" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc22d845ec31870b4ebb70f2c84e757a/href">https://medium.com/media/bc22d845ec31870b4ebb70f2c84e757a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e411282bb75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop a phone validator with Go using dev container — 3]]></title>
            <link>https://medium.com/@daskinnyman/develop-a-phone-validator-with-go-using-dev-container-3-3930bc604454?source=rss-ec82708519ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3930bc604454</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 10:02:27 GMT</pubDate>
            <atom:updated>2023-08-22T13:23:09.540Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Develop a phone validator with Go using dev container — 3</strong></h3><blockquote><strong>This series of post is also available on my blog:<br> </strong><a href="https://daskinnyman.vercel.app/"><strong>https://daskinnyman.vercel.app/</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s464qmGERRrtq5SC" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We’ve learn about some architectural pattern to build a scalable back-end service. Now we will implement the service using (Service / Repository Pattern) from the <a href="https://medium.com/@daskinnyman/develop-an-api-with-go-using-dev-container-2-b5e6b5ccd93d">previous post</a>.</p><p>Our goal is to create a phone validation service, It will have one API endpoint which takes a phone number as input. And the API will send whether the input phone number is valid. To make the API able to communicate to DB, we will also save the validation result into the DB we setup in <a href="https://medium.com/@daskinnyman/develop-an-api-with-go-using-dev-container-1-fa43a9ab841a">part 1</a></p><p>We will create a folder called pkg, and this folder will contains our service, controller, repository and data model. Now we will have the folder structure below:</p><pre>phone_validator<br>├─ .devcontainer<br>│ ├─ .env<br>│ ├─ Dockerfile<br>│ ├─ devcontainer.json<br>│ └─ docker-compose.yml<br>├─ .gitignore<br>├─ go.mod<br>├─ go.sum<br>├─ main.go<br>└─ pkg</pre><h3>Create the DB model for the data to store</h3><p>First, we will define the data model for the validation result. We will create a db folder to contain our data models. In the db folder, let’s create a file called phoneNumber.go which will be responsible for create and provide the ability for gorm to manipulate the phoneNumber table in the DB.</p><pre>package db<br><br>type PhoneNumber struct {<br><br>   PhoneNumber string `gorm:&quot;primaryKey&quot; json:&quot;phone_number&quot;`<br>   <br>   Valid bool<br>}</pre><p>As you could see, we create a struct call PhoneNumber and specify the fields.<br>We use gorm:”primaryKey” to assign the PhoneNumber field as primary key since we expect the same phone number will have the same validation result.<br>And use json:”phone_number” to make the PhoneNumber field parse to phone_number when sending the JSON to client. Also, we have to store the validation result, so we specified a field named Valid with a boolean for it.</p><h3>Design and implement the interface for repository layer</h3><p>We have create our DB model, now let’s design the repository layer for our service.<br>The repository layer is responsible for provide a abstraction between our service logic and database implementation. With repository layer the service layer just need to focus on the function input and the output with the repository, regardless the DB is SQL or non-SQL and what query command should be used.</p><p>For our service, we need to abstract on two DB implementation:<br>1. create a validation result with the phoneNumber<br>2. get a validation result of the phoneNumber</p><p>Inside the pkg folder, let’s create a folder called repositories. And then create a folder inside repositories folder, called entities. Then we will create a phoneNumber.go file inside the entities folder.</p><pre>package entities<br><br>type PhoneNumber struct {<br><br>   PhoneNumber string<br>   <br>   Valid bool<br>   <br>   UpdatedAt int<br>}</pre><p>The repository will convert the db models to the entities, and the entities will be used across the services. By doing this, we can get rid of the DB implementation and focus on the logic we care about. Then we will create a phoneNumber.go file inside the repositories folder.</p><p>Once we create the file, we can start design our interface for the repository layer.</p><pre>package repositories<br><br>import (<br>   &quot;phone_validator/pkg/repositories/entities&quot;<br>   <br>   &quot;gorm.io/gorm&quot;<br>)<br><br>type PhoneNumberRepository interface {<br>  <br>   // create a validation result with the phoneNumber<br>   CreatePhoneNumberResult(phoneNumber entities.PhoneNumber) (entities.PhoneNumber, error)<br>   <br>   // get a validation result of the phoneNumber<br>   GetPhoneNumberResult(phoneNumber string) (entities.PhoneNumber, error)<br>}<br><br>type phoneNumberRepository struct {<br>   db *gorm.DB<br>}</pre><p>The CreatePhoneNumberResult should receive a phoneNumber model to create the validation result and it should return the model once created.</p><p>The GetPhoneNumberResult should receive a phone number to query the result from database.</p><h3>Implement the repository</h3><p>Now, we had finished the design of our repository, let’s implement the repository logic</p><pre>package repositories<br><br>import (<br>   &quot;phone_validator/pkg/repositories/entities&quot;<br>   <br>   models &quot;phone_validator/pkg/db&quot;<br>   <br>   &quot;gorm.io/gorm&quot;<br>  )<br><br><br>type PhoneNumberRepository interface {<br>   // The interface <br>}<br><br>type phoneNumberRepository struct {<br>   // The struct<br>}<br><br>//Step 1. create a function to create the repository instance, and inject the DB into the instance<br>func NewPhoneNumberResultRepository(db *gorm.DB) PhoneNumberRepository {<br>   return &amp;phoneNumberRepository{<br>   db: db,<br>   }<br>}<br><br>//Step 2: immplment the functions inside the PhoneNumberRepository interface<br>func (r *phoneNumberRepository) CreatePhoneNumberResult(phoneNumber entities.PhoneNumber) (entities.PhoneNumber, error) {<br>   //Map the PhoneNumber entity to PhoneNumber Db model<br>   phoneNumberToCreate := models.PhoneNumber{ <br>      PhoneNumber: phoneNumber.PhoneNumber,<br>      Valid: phoneNumber.Valid,<br>      UpdatedAt: phoneNumber.UpdatedAt,<br>   }<br>  <br>   // Save the PhoneNumber Db model<br>   err := r.db.Create(&amp;phoneNumberToCreate).Error<br>    <br>   if err != nil {<br>      return phoneNumber, err<br>   }<br>  <br>   // Map PhoneNumber Db model to PhoneNumber entity<br>   var phoneNumberEntity entities.PhoneNumber<br>   phoneNumberEntity.PhoneNumber = phoneNumberToCreate.PhoneNumber<br>   phoneNumberEntity.Valid = phoneNumberToCreate.Valid<br>   phoneNumberEntity.UpdatedAt = phoneNumberToCreate.UpdatedAt<br>   <br>   return phoneNumberEntity, nil<br>}<br><br>func (r *phoneNumberRepository) GetPhoneNumberResult(phoneNumber string) (entities.PhoneNumber, error) {<br>   var phoneNumberRes models.PhoneNumber<br>   // Query the phone number<br>   r.db.First(&amp;phoneNumberRes, phoneNumber)<br>   <br>   var phoneNumberEntity entities.PhoneNumber<br>   <br>   // Map PhoneNumber Db model to PhoneNumber entity<br>   phoneNumberEntity.PhoneNumber = phoneNumberRes.PhoneNumber<br>   phoneNumberEntity.Valid = phoneNumberRes.Valid<br>   phoneNumberEntity.UpdatedAt = phoneNumberRes.UpdatedAt<br>   <br>   return phoneNumberEntity, nil<br>}</pre><h3>Design and implement the interface for service layer</h3><p>We’ve done the repository layer to retrieve and convert the data from DB to the entity. Next we will create the service layer. The service layer is a place for implement the business logic. it stands in between the controller layer and repository layer.</p><h3>Design service layer</h3><p>First, let’s create a folder called services. Inside the pkg folder, let’s create a folder called services. And then create a folder inside services folder, called dtos. Then we will create a phoneNumber.go file inside the dtos folder.</p><pre>package dtos<br><br>type ValidatePhoneNumberRequest struct {<br><br>   PhoneNumber string `json:&quot;phone_number&quot;`<br> <br>}</pre><p>Dtos stands for <strong>D</strong>ata<strong> T</strong>ransfer <strong>O</strong>bject. It is used for transfer the data between the controller and service layer. In our project, we will use the dto to handle the phone number from API from user and transfer to service to do more calculation.</p><p>Next, we will create a file called phoneNumber.go inside the services folder. And start design the interface for our service.</p><pre>package serivces<br><br>import (<br>   &quot;phone_validator/pkg/repositories&quot;<br>   &quot;phone_validator/pkg/serivces/dtos&quot;<br>)<br><br>type PhoneValidatorService interface {<br>   ValidatePhoneNumber(req dtos.ValidatePhoneNumberRequest) (bool, error)<br>}<br>  <br>type phoneValidatorService struct {<br>   storage repositories.PhoneNumberRepository<br>}</pre><p>Our PhoneValidatorService will expose a function for controller which will handle the validation and save the result.</p><p>We will use the <a href="https://github.com/nyaruka/phonenumbers">phone numbers</a> library to validate our phone number. So let’s install it first.</p><pre>go get -u github.com/nyaruka/phonenumbers</pre><p>Then, In the same phoneNumber.go file, we will started to implement the service.</p><pre>package serivces<br><br>import (<br>   &quot;phone_validator/pkg/repositories&quot;<br>   &quot;phone_validator/pkg/repositories/entities&quot;<br>   &quot;phone_validator/pkg/serivces/dtos&quot;<br>   <br>   &quot;github.com/nyaruka/phonenumbers&quot;<br>)<br><br><br>type PhoneValidatorService interface {<br>   // The interface <br>}<br><br>type phoneValidatorService struct {<br>   // The struct<br>}<br><br>// Step 2: create the constructor for the service<br>func NewPhoneValidatorService(repo repositories.PhoneNumberRepository) PhoneValidatorService {<br>   return &amp;phoneValidatorService{ <br>      storage: repo,<br>   }<br>}<br><br>// Step 3: implement the methods for the service<br>func (p *phoneValidatorService) ValidatePhoneNumber(req dtos.ValidatePhoneNumberRequest) (bool, error) {<br>   phoneNumberToValidate := req.PhoneNumber<br>   // 1. Check if phone number is empty or spaces<br>   if len(phoneNumberToValidate) == 0 || phoneNumberToValidate == &quot; &quot; {<br>      return false, nil<br>   }<br>  <br>   // 2. Check if phone number is existing in the database<br>   phoneRecord, err := p.storage.GetPhoneNumberResult(phoneNumberToValidate)<br>  <br>   if err != nil {<br>      return false, err<br>   }<br>  <br>   // 3. Return true if phone number is existing in the database<br>   if phoneRecord.PhoneNumber != &quot;&quot; {<br>      return phoneRecord.Valid, nil<br>   }<br>  <br>   // I&#39;m in Taiwan so I&#39;ll use TW to validate phone number in Taiwan, feel free to change to any other code<br>   // 4. parse the phone number <br>   phoneNumber, err := phonenumbers.Parse(phoneNumberToValidate, &quot;TW&quot;)<br>  <br>   if err != nil {<br>      return false, err<br>   }<br>  <br>   isValid := phonenumbers.IsValidNumberForRegion(phoneNumber, &quot;TW&quot;)<br>  <br>   // 5. Save the phone number to the database<br>   phoneNumberToSave := entities.PhoneNumber{<br>      PhoneNumber: phoneNumberToValidate,<br>      Valid: isValid,<br>   }<br>   <br>   res, err := p.storage.CreatePhoneNumberResult(phoneNumberToSave)<br>  <br>   if err != nil {<br>      return false, err<br>   }<br>  <br>   return res.Valid, nil<br>}</pre><h3>Implement the Controller layer</h3><p>We had implement the repository layer for retrieve and convert the data from DB and service layer for the API functionality. Now, let’s create the outermost layer for our API —the controller. Our controller will be responsible for parsing the data from the HTTP request body, and sent back the validation result.</p><p>Inside the pkg folder, let’s create a folder called controllers. Then we will create a phoneNumber.go file inside the controllers folder. And we will start to write the logic for our controller.</p><p>Our controller will expose one API endpoint the client /api/validate, this endpoint will receive a JSON body and parse the data then handover the data to our service.</p><pre>package controllers<br><br>import (<br>   &quot;log&quot;<br>   &quot;net/http&quot;<br>   &quot;phone_validator/pkg/serivces&quot;<br>   &quot;phone_validator/pkg/serivces/dtos&quot;<br>   &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>  <br><br>// Step 1: define the struct for the controller<br>type PhoneValidatorHandler struct {<br><br>  PhoneValidatorService serivces.PhoneValidatorService<br><br>}<br><br>  <br><br>// Step 2: create the constructor for the controller<br>func NewPhoneValidatorHandler(e *gin.Engine, phoneValidatorService serivces.PhoneValidatorService) {<br>   handler := &amp;PhoneValidatorHandler{<br>     PhoneValidatorService: phoneValidatorService,<br>   }<br>  <br>      // Register the endpoint<br>   e.POST(&quot;/api/validate&quot;, handler.ValidatePhoneNumber)<br>}<br>  <br>  // Step 3: implement the methods for the controller<br>func (handler *PhoneValidatorHandler) ValidatePhoneNumber(c *gin.Context) {<br>   <br>   c.Header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>   var phoneToValidate dtos.ValidatePhoneNumberRequest<br>   <br>   // 4. Get the request body<br>   err := c.ShouldBindJSON(&amp;phoneToValidate)<br>   <br>   if err != nil {<br>      log.Printf(&quot;handler error: %v&quot;, err)<br>      c.JSON(http.StatusBadRequest, nil)<br>      return<br>   }<br>   <br>   // 5. Call the service<br>   isValid, err := handler.PhoneValidatorService.ValidatePhoneNumber(phoneToValidate)<br>   <br>   if err != nil {<br>      log.Printf(&quot;handler error: %v&quot;, err)<br>      c.JSON(http.StatusInternalServerError, gin.H{<br>      &quot;error&quot;: err.Error(),<br>      })<br>  <br>      return<br>   }<br>   <br>   // 6. Return the response<br>   c.JSON(http.StatusOK, gin.H{<br>      &quot;error&quot;: nil,<br>      &quot;valid&quot;: isValid,<br>   })<br>}</pre><h3>Bring it all together</h3><p>Great! So far we have create all the things we need for our API. Let’s combine them together to make sure the API works as expected!</p><p>Back to our main.go file. We will instantiate the the repository, service and controller inside the run() function.</p><pre>package main<br><br>import (<br>   &quot;fmt&quot;<br>   &quot;os&quot;<br>   <br>   &quot;phone_validator/pkg/controllers&quot;<br>   models &quot;phone_validator/pkg/db&quot;<br>   &quot;phone_validator/pkg/repositories&quot;<br>   &quot;phone_validator/pkg/serivces&quot;<br>  <br>   &quot;github.com/gin-contrib/cors&quot;<br>   &quot;github.com/gin-gonic/gin&quot;<br>   &quot;gorm.io/driver/mysql&quot;<br>   &quot;gorm.io/gorm&quot;<br>)<br><br>// Entry point<br>func main() {/**/}<br><br>func run() error {<br>   dsn := &quot;root:root@tcp(127.0.0.1:3306)/phone_validator?charset=utf8mb4&amp;parseTime=True&amp;loc=Local&quot;<br>   <br>   db, err := setUpDbConnection(dsn)<br>  <br>   // This will create the phone number table in the database<br>   db.AutoMigrate(&amp;models.PhoneNumber{})<br>   <br>   if err != nil {<br>      return err<br>   }<br>  <br>   // Instantiate the repository and inject the db instance<br>   phoneRepo := repositories.NewPhoneNumberResultRepository(db)<br>  <br>   // Instantiate the service and inject the repository instance<br>   phoneValidatorService := serivces.NewPhoneValidatorService(phoneRepo)<br>   <br>   // Init gin router to handle API call<br>   router := gin.Default()<br>  <br>   // Set up cors<br>   router.Use(cors.Default())<br>  <br>   // Instantiate the controller and inject the service instance and gin router instance.<br>   controllers.CreatePhoneValidatorHandler(router, phoneValidatorService)<br>  <br>   // Start the server at port 3000<br>   err = router.Run(&quot;:3000&quot;)<br>  <br>   if err != nil {<br>      fmt.Printf(&quot;Server - there was an error calling Run on router: %v&quot;, err)<br>      return err<br>   }<br>  <br>   return nil<br>}<br><br>func setUpDbConnection(connectionString string) (*gorm.DB, error) {/**/}</pre><h3>Run the server and test the API</h3><p>Now let’s try to run the server and test our API.</p><p>In terminal type the command below:</p><pre>go run main.go</pre><p>And open <a href="https://www.postman.com/">Postman</a> fill in <a href="http://localhost:3000/api/validate%60">http://localhost:3000/api/validate</a> as the URL and choose POST . Remember the check the raw radio button in the body tab and select the JSON for the body type. Then fill in the text area below with the number you wish to validate. Then click send.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86h1HhLGVkf3Rl6b1eBwLw.png" /></figure><p>You should see the result like this since the number is not valid.</p><pre>{<br> &quot;error&quot;: null,<br> &quot;valid&quot;: false<br>}</pre><p>You can try another phone number and it should sent back the correct response according to your input. If not, please go to the service layer and see if you change the TW code to where your input phone number belong in below lines.</p><pre> // I&#39;m in Taiwan so I&#39;ll use TW to validate phone number in Taiwan, feel free to change to any other code<br> // 4. parse the phone number <br> phoneNumber, err := phonenumbers.Parse(phoneNumberToValidate, &quot;TW&quot;)<br><br> if err != nil {<br>  return false, err<br> }<br><br> isValid := phonenumbers.IsValidNumberForRegion(phoneNumber, &quot;TW&quot;)</pre><h3>Summary</h3><p>This is the last article for the Develop a phone validator with Go using dev container.</p><p>In this series we have learn how to:<br>1. Write basic docker-compose file to integrate our server and database.<br>2. Use <a href="https://gorm.io/index.html">gorm</a> as an ORM to communicate with the database.<br>3. The basic concept for the N-teir architecture, and simple Dependency injection with Go.<br>4. How to write a scalable Go service.</p><p>If you want to go deeper, here are things you can try base on this project.<br>1. Add OpenAPI documentation, For example: Swagger.<br>2. Write unit test for this API service.<br>3. validate the user input on controller.</p><h4><strong>📕 Previous Posts:</strong></h4><p>1️⃣ <a href="https://medium.com/@daskinnyman/develop-an-api-with-go-using-dev-container-1-fa43a9ab841a">Develop an API with Go using dev container — 1</a></p><p>2️⃣ <a href="https://medium.com/@daskinnyman/develop-an-api-with-go-using-dev-container-2-b5e6b5ccd93d">Develop an API with Go using dev container — 2</a></p><p>If you like my post, please press the like button.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Falex940131%2Fbutton&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fin%2Flike%2Falex940131&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Flikecoin-foundation.appspot.com%2Flikecoin_store_user_alex940131_main%3FGoogleAccessId%3Dlikecoin-api-public%2540likecoin-foundation.iam.gserviceaccount.com%26Expires%3D2430432000%26Signature%3DbdYzKBGHrDRBllBGJ%252F7wWuE995S40I%252B9%252Flxucpsyugs2K5DVWad4ARcRWgpYtp9btQSfKCiyzbP1ZaiGiasDsEn5TcAjZTwTweZsUdoLiuaL8v8dXheoThnp7%252FWQXWkRDChifa8INSdN6DXS18PlV%252FOOjkUyOz%252BxmnCrwYoa2E3qJ2Atey52ghkb7Eot6MFvqpHJQzufj1546jwD0uF7w6r%252Bbbse47owXDra2pwFGnZ8KPpVy5IjAaKdMJ5J5KpIRFyRZ546kEs3j3lVduqkgYuyLFQ%252FRF8dk47rHnX5xBL6bN05ILoQOCuKDtSVQoOhKtrDXXwS6rjf9adGAc6hzA%253D%253D%2607970c2&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="360" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc22d845ec31870b4ebb70f2c84e757a/href">https://medium.com/media/bc22d845ec31870b4ebb70f2c84e757a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3930bc604454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop an API with Go using dev container — 2]]></title>
            <link>https://medium.com/@daskinnyman/develop-an-api-with-go-using-dev-container-2-b5e6b5ccd93d?source=rss-ec82708519ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5e6b5ccd93d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 23:31:45 GMT</pubDate>
            <atom:updated>2023-08-22T13:22:29.915Z</atom:updated>
            <content:encoded><![CDATA[<h3>Develop an API with Go using dev container — 2</h3><blockquote><em>This series of post is also available on my blog: </em><a href="https://daskinnyman.vercel.app/"><em>https://daskinnyman.vercel.app/</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t2uzo_uS-dorW8JW" /><figcaption>Photo by <a href="https://unsplash.com/@dianamia?utm_source=medium&amp;utm_medium=referral">C Dustin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the <a href="https://medium.com/@daskinnyman/develop-an-api-with-go-using-dev-container-1-fa43a9ab841a">previous post</a>, we set up a development environment using a dev-container and verified that our Go code successfully connects to MariaDB. In this chapter, we will discuss an architectural pattern for the API we are building. Before we get started, I’ll introduce a pattern called “Fat controllers”.</p><h3>The fat controllers</h3><p>Fat controllers are controllers that contain all related business logic and handle request/response-related tasks.</p><p>However, maintaining the codebase with fat controllers can become difficult as the project scales up. The downsides of this pattern include:</p><ol><li>Difficult to test</li><li>May contain lots of duplicate logic</li><li>Less flexibility</li><li>Does not follow the Single Responsibility Principle (SRP)</li></ol><p><em>While it is acceptable to build this kind of controller with a demo or proof-of-concept project, if you truly care about maintainability and scalability, I suggest avoiding this pattern in production.</em></p><h3>Service / Repository Pattern</h3><p>As I will demonstrate a more maintainable and scalable way of writing a Go API, I will implement it using the Service/Repository Pattern.</p><figure><img alt="diagram of shopping cart API with Service/Repository Pattern" src="https://cdn-images-1.medium.com/max/1024/1*MZ7UndLmHopt263YewVUtg.png" /><figcaption>diagram of shopping cart API with Service/Repository Pattern</figcaption></figure><p>The diagram demonstrates a cart API using the Service/Repository Pattern. We separate the “Fat controller” into three layers based on their responsibilities.</p><p><strong>Controller:</strong></p><ol><li>check whether a user can access the specific resource.</li><li>check whether a user has permission to use the specific resource.</li><li>validating the incoming request .</li><li>handle error.</li><li>send response.</li><li>place to write Open API annotation</li></ol><p><strong>Service:</strong></p><ol><li>process the business logic</li></ol><p><strong>Repository:</strong></p><ol><li>Provide a layer to abstract the implementation to communicate the DB</li></ol><p>By encapsulating logic in the service layer, we can make it reusable across other services. Using the repository to hide the implementation from the database ensures that swapping out different types of databases will not break the service or controller layer.</p><p>We can improve unit testing by mocking the service and repository layers that are not related to the unit test. However, how can we elegantly swap the dependencies of a specific service or controller? The answer is “<strong>Dependency injection (DI)</strong>“.</p><h3>Dependency injection (DI)</h3><p>Dependency injection is a method to decouple the dependency between two related classes.</p><p>First, we will use the interface to describe the method of the class. Then, we will implement the class method according to the interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxEIPDZuQjPD42MvxGSh3g.png" /><figcaption>UML diagram of DI of shopping cart API with Service/Repository Pattern</figcaption></figure><p><em>You can think of this interface as an “API document” between the services and controller. It promises the consumed service that it will output a specific value with the specific input.</em></p><p>Once we have created the interface to describe the service, we can inject it into the consumed service. Because the injected service will implement the interface (the API document), you can swap any service that implements the specific interface. Since the interface is not changed, we can expect the service to output the same type of value for the same input.</p><figure><img alt="UML diagram of DI of shopping cart API with Service/Repository Pattern using mock service" src="https://cdn-images-1.medium.com/max/1024/1*6DSCZKis9NNS6HWLSSUWUQ.png" /><figcaption>UML diagram of DI of shopping cart API with Service/Repository Pattern using mock service</figcaption></figure><p>With Dependency Injection, we can replace a service with a mock service that implements the same interface during unit testing</p><h3>Summary</h3><p>We have gone through the basic terminology and techniques that will be used to implement our Go API. Go has many awesome DI libraries, such as <a href="https://github.com/google/wire">Wire</a> and <a href="https://github.com/uber-go/dig">dig</a>. However, in this document, we will implement our own DI to better understand what DI really does in the next chapter.</p><p>First, we will use the interface to describe the method of the class. Then, we will implement the class method according to the interface.</p><p>If you like my post, please press the like button.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Falex940131%2Fbutton&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fin%2Flike%2Falex940131&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Flikecoin-foundation.appspot.com%2Flikecoin_store_user_alex940131_main%3FGoogleAccessId%3Dlikecoin-api-public%2540likecoin-foundation.iam.gserviceaccount.com%26Expires%3D2430432000%26Signature%3DbdYzKBGHrDRBllBGJ%252F7wWuE995S40I%252B9%252Flxucpsyugs2K5DVWad4ARcRWgpYtp9btQSfKCiyzbP1ZaiGiasDsEn5TcAjZTwTweZsUdoLiuaL8v8dXheoThnp7%252FWQXWkRDChifa8INSdN6DXS18PlV%252FOOjkUyOz%252BxmnCrwYoa2E3qJ2Atey52ghkb7Eot6MFvqpHJQzufj1546jwD0uF7w6r%252Bbbse47owXDra2pwFGnZ8KPpVy5IjAaKdMJ5J5KpIRFyRZ546kEs3j3lVduqkgYuyLFQ%252FRF8dk47rHnX5xBL6bN05ILoQOCuKDtSVQoOhKtrDXXwS6rjf9adGAc6hzA%253D%253D%2607970c2&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="360" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc22d845ec31870b4ebb70f2c84e757a/href">https://medium.com/media/bc22d845ec31870b4ebb70f2c84e757a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5e6b5ccd93d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop an API with Go using dev container — 1]]></title>
            <link>https://medium.com/@daskinnyman/develop-an-api-with-go-using-dev-container-1-fa43a9ab841a?source=rss-ec82708519ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa43a9ab841a</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Alex]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 16:48:55 GMT</pubDate>
            <atom:updated>2023-08-22T13:21:59.639Z</atom:updated>
            <content:encoded><![CDATA[<h3>Develop an API with Go using dev container — 1</h3><blockquote>This series of post is also available on my blog: <a href="https://daskinnyman.vercel.app/">https://daskinnyman.vercel.app/</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*seV6GZYgMp3phv34" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Container changes the software industry, it empower us to have more robust deployment process. Sometimes it is painful to configure the development environment as a developer. When there are some newcomers we might face some situation. Like the development environment can only be setup with some specific version of dependencies. But the correct version of dependencies has been lost or outdated with the document.</p><p>In this case, dev container can help you to setup the environment and manage the dependencies with the docker-compose file. It creates a portable development environment and you can share it via check-in the dev container config files into the version control. Which provide the version control to development environment.</p><p>We will use a API server with MariaDB to demonstrate it. The API server will be a phone validator, which allows user input a phone number and the API will check if the phone number is valid and then store the phone number and result to the DB.</p><p>If the user input the same the phone number exist in DB we will sent the result store in DB instead of validate it again.</p><p>Prerequisite:</p><p>1. vscode</p><p>2. Knowledge of docker</p><p>3. Knowledge of MariaDB</p><h3><strong>Setting up VS code dev container</strong></h3><p>create a folder in root called .devcontainer, in the folder we will create files below to config our dev container.</p><p>DockerFile</p><pre>FROM mcr.microsoft.com/devcontainers/go:1–1.20-bullseye</pre><p>.env</p><pre>MYSQL_USER=root<br>MYSQL_ROOT_PASSWORD=root<br>MYSQL_PASSWORD=root<br>MYSQL_DATABASE=phone_validator</pre><p>docker-compose.yml</p><pre>version: ‘3.8’<br><br>volumes:<br>  mariadb-data:<br>services:<br>  app:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile # We will use the DockerFile inroot to build the app<br>    env_file:<br>      - .env # Loads the .env file to provide the environment varable<br>    volumes:<br>      - ../..:/workspaces:cached<br>    command: sleep infinity<br>    network_mode: service:db # Make sure the app runs on the same as the database container<br>  db:<br>    image: mariadb:latest # Use the latest mariaDB. You can also specify a version here<br>    restart: unless-stopped<br>    volumes:<br>      - mariadb-data:/var/lib/mysql<br>    env_file:<br>      - .env # Loads the .env file to provide the environment varable</pre><p>devcontainer.json</p><pre>{<br>  &quot;name&quot;: &quot;phone validator&quot;,<br>  // Specified we will use docker-compose.yml as the dev container.<br>  &quot;dockerComposeFile&quot;: &quot;docker-compose.yml&quot;,<br>  &quot;service&quot;: &quot;app&quot;,<br>  &quot;workspaceFolder&quot;: &quot;/workspaces/${localWorkspaceFolderBasename}&quot;,<br>  // We will expose 3000,3306 to out localhost, so that we can access the API and inspect the DB using any DBMS client.<br>  &quot;forwardPorts&quot;: [<br>    3000,<br>    3306<br>  ],<br>  &quot;customizations&quot;: {<br>    &quot;vscode&quot;: {<br>    &quot;extensions&quot;: [<br>      &quot;premparihar.gotestexplorer&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>Now we done the configuration, let’s start the dev container by clicking the purple button at the bottom left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6b4u8z0p0XdQQX1h3hKnNg.png" /></figure><p>And click the Reopen in container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isAEu09ioCMs30muj70-JQ.png" /></figure><p>Then you will see the purple button turns into this when the dev container created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFR2vMmd3duPTaf8oTGf5g.png" /></figure><p>The dev container is up and running. Let’s write our code to implement the DB connection.</p><h3><strong>Implement the DB connection</strong></h3><p><strong>Create the project</strong></p><p>To get started, we will need to scaffold the project.</p><p>Let’s do it step by step:</p><p>init module</p><pre>go mod init phone_validator</pre><p><strong>Install dependencies</strong></p><p>We will use <a href="https://github.com/gin-gonic/gin">gin</a> as a framework to implement the API server.</p><p>To install gin</p><pre>go get -u github.com/gin-gonic/gin</pre><p>We will use <a href="https://gorm.io/index.html">gorm</a> as a framework to implement the API server.</p><p>To install gorm and mysql driver</p><pre>go get -u gorm.io/gorm<br>go get -u gorm.io/driver/mysql</pre><p><strong>Write first lines of code</strong></p><p>create main.go under root folder and type the code below in main.go</p><pre>func main(){<br>  println(&quot;Hello world&quot;)<br>}</pre><p>run go</p><pre>go run main.go</pre><p>If you see the Hello world in the terminal, we can move on the create our phone validator APIs.</p><p><strong>Create db connection</strong></p><p>We try if our go code can connect our MariaDB.</p><p>Open main.go. Let’s create the entry point of our code and a function that runs the go HTTP server</p><pre>package main<br><br>// Entry point<br>func main(){<br>}<br><br>func run(){<br>}</pre><p>Then we will write a function called setUpDbConnection which takes a connectionString as a string parameter to set up the connection with DB. And the function will either return a gorm DB instance and an error instance.</p><pre>package main<br><br>import (<br>  &quot;fmt&quot;<br>  &quot;gorm.io/driver/mysql&quot;<br>  &quot;gorm.io/gorm&quot;<br>)<br><br>// Entry point<br>func main(){/*****/}<br><br>func run(){/*****/}<br><br>func setUpDbConnection(connectionString string) (*gorm.DB, error) {<br>  db, err := gorm.Open(mysql.Open(connectionString), &amp;gorm.Config{})<br><br>  if err != nil {<br>    return nil, err<br>  }<br><br>  fmt.Println(&quot;Successfully created connection to database&quot;)<br><br>  return db, nil<br>}</pre><p>Next, we will write some code in run() function to send the connection string to setUpDbConnection and retrieve the gorm db instance. Also run function will catch the error and return it if there are any.</p><pre>package main<br><br>import (<br>  &quot;fmt&quot;<br>  &quot;gorm.io/driver/mysql&quot;<br>  &quot;gorm.io/gorm&quot;<br>)<br><br>// Entry point<br>func main() {/**/}<br><br>func run() error {<br>  dsn := &quot;root:root@tcp(127.0.0.1:3306)/phone_validator?charset=utf8mb4&amp;parseTime=True&amp;loc=Local&quot;<br>  db, err := setUpDbConnection(dsn)<br>  <br>  if err != nil {<br>    return err<br>  }<br>  <br>  fmt.Printf(&quot;this is the db: %v&quot;, db)<br>  return nil<br>}<br><br>func setUpDbConnection(connectionString string) (*gorm.DB, error) {/**/}</pre><p>Finally, we will called the run() function in main(). its will run the code to setup DB connection with connection string or print out the Error and exit the program if there are any error thrown by run() function.</p><pre>package main<br><br>import (<br>  &quot;fmt&quot;<br>  &quot;os&quot;<br>  &quot;gorm.io/driver/mysql&quot;<br>  &quot;gorm.io/gorm&quot;<br>)<br><br>// Entry point<br>func main() {<br>  if err := run(); err != nil {<br>  fmt.Fprintf(os.Stderr, &quot;this is the startup error: %s\\n&quot;, err)<br>  os.Exit(1)<br>  }<br>}<br><br>func run() error {/**/}<br><br>func setUpDbConnection(connectionString string) (*gorm.DB, error) {/**/}</pre><p>Now you should be able to run the code with typing go run main.go in terminal. And you will see the output like this:</p><pre>Successfully created connection to database<br>this is the db: &amp;{0x********** &lt;nil&gt; 0 0x********** 1}</pre><p>Now we have created the dev container and write our first code for our API. Next we will dive into the design and implementation of the API server and interact with the DB using gorm.</p><p>If you like my post, please press the like button.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbutton.like.co%2Fin%2Fembed%2Falex940131%2Fbutton&amp;display_name=LikeCoin&amp;url=https%3A%2F%2Fbutton.like.co%2Fin%2Flike%2Falex940131&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Flikecoin-foundation.appspot.com%2Flikecoin_store_user_alex940131_main%3FGoogleAccessId%3Dlikecoin-api-public%2540likecoin-foundation.iam.gserviceaccount.com%26Expires%3D2430432000%26Signature%3DbdYzKBGHrDRBllBGJ%252F7wWuE995S40I%252B9%252Flxucpsyugs2K5DVWad4ARcRWgpYtp9btQSfKCiyzbP1ZaiGiasDsEn5TcAjZTwTweZsUdoLiuaL8v8dXheoThnp7%252FWQXWkRDChifa8INSdN6DXS18PlV%252FOOjkUyOz%252BxmnCrwYoa2E3qJ2Atey52ghkb7Eot6MFvqpHJQzufj1546jwD0uF7w6r%252Bbbse47owXDra2pwFGnZ8KPpVy5IjAaKdMJ5J5KpIRFyRZ546kEs3j3lVduqkgYuyLFQ%252FRF8dk47rHnX5xBL6bN05ILoQOCuKDtSVQoOhKtrDXXwS6rjf9adGAc6hzA%253D%253D%2607970c2&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=like" width="360" height="212" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc22d845ec31870b4ebb70f2c84e757a/href">https://medium.com/media/bc22d845ec31870b4ebb70f2c84e757a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa43a9ab841a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>