<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: yanoandri</title>
    <description>The latest articles on DEV Community by yanoandri (@yanoandri).</description>
    <link>https://dev.to/yanoandri</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F182265%2F882012b6-9a33-4bef-9dea-5c8ada2808ce.png</url>
      <title>DEV Community: yanoandri</title>
      <link>https://dev.to/yanoandri</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/yanoandri"/>
    <language>en</language>
    <item>
      <title>Mock Database Unit Test with Mockery in Go</title>
      <dc:creator>yanoandri</dc:creator>
      <pubDate>Sun, 20 Feb 2022 17:03:17 +0000</pubDate>
      <link>https://dev.to/yanoandri/mock-database-unit-test-with-mockery-in-go-42cl</link>
      <guid>https://dev.to/yanoandri/mock-database-unit-test-with-mockery-in-go-42cl</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Hi everyone, in this article, we will learn how to create unit test in Go, using mockery to testing a project's dependency.  We often use mock testing as we unit test a function with another dependencies such as database, so we will learn on how to create it by using example that i'd wrote in &lt;a href="https://dev.to/yanoandri/database-handling-with-golang-gorm-crud-handling-4c66"&gt;here&lt;/a&gt; with the steps by steps on how to refactor, create unit test and using the mockery itself, let's get start into it!&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Mockery?
&lt;/h2&gt;

&lt;p&gt;Mockery provide us with the command to generate mock functions, that we can use for unit testing, so as a results we don't have to write our mock function from scratch, and it will be automatically provided by searching into our interface functions, inside our project's dependencies&lt;/p&gt;

&lt;p&gt;To make this tutorial easier, we will prepare to refactor our code from previous article first, create a unit test, run the mockery and start using it in our unit test file in Go&lt;/p&gt;

&lt;h2&gt;
  
  
  Refactor
&lt;/h2&gt;

&lt;p&gt;first thing to do, we're going to have a look into our old code, we going to define the interface in it, how do we do it? by creating a new root folder with name of &lt;code&gt;repository&lt;/code&gt;, from here this is what we call when we use our database dependency. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

- config
 |_ config.go
- models
 |_ payment.go
- repository
 |_ payment.go
- test.go


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;we will start by defining the interface in &lt;code&gt;payment.go&lt;/code&gt; inside our repository folder&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

type IPaymentRepository interface {
    UpdatePayment(id string, payment models.Payment) (models.Payment, error)
    DeletePayment(id string) (int64, error)
    SelectPaymentWIthId(id string) (models.Payment, error)
    CreatePayment(payment models.Payment) (int64, error)
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;since we are going to separate the database dependency from the function, we're going to create a struct that act to hold our database dependency value&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

type Repository struct {
    Database *gorm.DB
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;then we move all the functions except the main one, inside our &lt;code&gt;payment.go&lt;/code&gt;, the complete repository will look like this&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package repository

import (
    "errors"

    "github.com/yanoandri/simple-goorm/models"
    "gorm.io/gorm"
)

type IPaymentRepository interface {
    UpdatePayment(id string, payment models.Payment) (models.Payment, error)
    DeletePayment(id string) (int64, error)
    SelectPaymentWIthId(id string) (models.Payment, error)
    CreatePayment(payment models.Payment) (int64, error)
}

type Repository struct {
    Database *gorm.DB
}

func (repo Repository) UpdatePayment(id string, payment models.Payment) (models.Payment, error) {
    var updatePayment models.Payment
    result := repo.Database.Model(&amp;amp;updatePayment).Where("id = ?", id).Updates(payment)
    if result.RowsAffected == 0 {
        return models.Payment{}, errors.New("payment data not update")
    }
    return updatePayment, nil
}

func (repo Repository) DeletePayment(id string) (int64, error) {
    var deletedPayment models.Payment
    result := repo.Database.Where("id = ?", id).Delete(&amp;amp;deletedPayment)
    if result.RowsAffected == 0 {
        return 0, errors.New("payment data not update")
    }
    return result.RowsAffected, nil
}

func (repo Repository) SelectPaymentWIthId(id string) (models.Payment, error) {
    var payment models.Payment
    result := repo.Database.First(&amp;amp;payment, "id = ?", id)
    if result.RowsAffected == 0 {
        return models.Payment{}, errors.New("payment data not found")
    }
    return payment, nil
}

func (repo Repository) CreatePayment(payment models.Payment) (int64, error) {
    result := repo.Database.Create(&amp;amp;payment)
    if result.RowsAffected == 0 {
        return 0, errors.New("payment not created")
    }
    return result.RowsAffected, nil
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;because we move all the functions into our repository folder, we will have to change the way to call our functions, we start to define which database value we want to hold in our struct inside our &lt;code&gt;test.go&lt;/code&gt; at the &lt;code&gt;main&lt;/code&gt; function&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

repo := repository.Repository{Database: db}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and from there we can use our functions, without putting any external dependency inside our parameters, for example&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// create a payment
payment := models.Payment{
    PaymentCode: "XXX-1",
    Name:        "Payment for item #1",
    Status:      "PENDING",
}

result, err := repo.CreatePayment(payment)


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Create a Unit Test File
&lt;/h2&gt;

&lt;p&gt;Luckily if we use VSCode, we can generate the unit test automatically by pressing &lt;code&gt;ctrl + p&lt;/code&gt; if you are in windows or &lt;code&gt;command + p&lt;/code&gt; and you will find the option to generate the functions like the screenshot below&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvcs2gn60jqpmzw1umsyf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvcs2gn60jqpmzw1umsyf.png" alt="go generate functions in vs code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and for the example we will create the test function of &lt;code&gt;CreatePayment&lt;/code&gt; by blocking the whole functions to generate it&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package repository

import (
    "testing"

    "github.com/yanoandri/simple-goorm/models"
)

func TestRepository_CreatePayment(t *testing.T) {
    type args struct {
        payment models.Payment
    }
    tests := []struct {
        name    string
        repo    Repository
        args    args
        want    int64
        wantErr bool
    }{
        // TODO: Add test cases.
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := tt.repo.CreatePayment(tt.args.payment)
            if (err != nil) != tt.wantErr {
                t.Errorf("Repository.CreatePayment() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if got != tt.want {
                t.Errorf("Repository.CreatePayment() = %v, want %v", got, tt.want)
            }
        })
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Mockery
&lt;/h2&gt;

&lt;p&gt;We will install mockery using our go command&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

go install github.com/vektra/mockery/v2@latest


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;after it finishes, we will create our mock functions by using mockery features to generate all of function mocks, by typing this command&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

mockery --all --keeptree


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;notice the &lt;code&gt;mocks&lt;/code&gt; folder of our project has been installed, and all of the functions has been mocked&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fake60xtoj8ynhev4fkwa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fake60xtoj8ynhev4fkwa.png" alt="Mocks Folder"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and this is one example of our &lt;code&gt;CreatePayment&lt;/code&gt; mock functions&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

// CreatePayment provides a mock function with given fields: payment
func (_m *IPaymentRepository) CreatePayment(payment models.Payment) (int64, error) {
    ret := _m.Called(payment)

    var r0 int64
    if rf, ok := ret.Get(0).(func(models.Payment) int64); ok {
        r0 = rf(payment)
    } else {
        r0 = ret.Get(0).(int64)
    }

    var r1 error
    if rf, ok := ret.Get(1).(func(models.Payment) error); ok {
        r1 = rf(payment)
    } else {
        r1 = ret.Error(1)
    }

    return r0, r1
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Write our test functions to use mocks
&lt;/h2&gt;

&lt;p&gt;Now let's include our mocked function to our unit test&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package repository

import (
    "errors"
    "testing"

    mocks "github.com/yanoandri/simple-goorm/mocks/repository"
    "github.com/yanoandri/simple-goorm/models"
)

func TestRepository_CreatePayment(t *testing.T) {
    type args struct {
        payment models.Payment
    }
    tests := []struct {
        name    string
        args    args
        want    int64
        wantErr bool
    }{
        // TODO: Add test cases.
        {
            name: "success_create_payment",
            args: args{
                models.Payment{
                    PaymentCode: "payment-code-011",
                    Status:      "PENDING",
                },
            },
            want:    1,
            wantErr: false,
        },
        {
            name: "failed_create_payment",
            args: args{
                models.Payment{},
            },
            want:    0,
            wantErr: true,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            repo := &amp;amp;mocks.IPaymentRepository{}
            if !tt.wantErr {
                repo.On("CreatePayment", tt.args.payment).Return(tt.want, nil)
            } else {
                repo.On("CreatePayment", tt.args.payment).Return(tt.want, errors.New("Failed to create payment"))
            }
            got, err := repo.CreatePayment(tt.args.payment)
            if (err != nil) != tt.wantErr {
                t.Errorf("Repository.CreatePayment() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if got != tt.want {
                t.Errorf("Repository.CreatePayment() = %v, want %v", got, tt.want)
            }
        })
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;notice the repo is missing, it is because we didn't have to use the actual dependencies of database, and we want to mock it in every test session.  And for now we will try to run our test by using command&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

go test ./... -v


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F71qg6f6u73zp4h7gj6l9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F71qg6f6u73zp4h7gj6l9.png" alt="Tested Results"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusions
&lt;/h2&gt;

&lt;p&gt;This is just one function as an example to use mocks functions in unit test, you can continue to make test for &lt;code&gt;UpdatePayment&lt;/code&gt;, &lt;code&gt;DeletePayment&lt;/code&gt; and also &lt;code&gt;SelectPaymentWIthId&lt;/code&gt;.  Mockery has provide us with easier way to generate our functions and as a results we can test our dependencies without creating the same functions twice from scratch, Hope this tutorial helps, and keep exploring! See ya!&lt;/p&gt;

&lt;p&gt;Source:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/yanoandri/simple-goorm/tree/mockery-tutorial" rel="noopener noreferrer"&gt;Repo&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>tutorial</category>
      <category>webdev</category>
      <category>programming</category>
      <category>go</category>
    </item>
    <item>
      <title>Playing with Environment Variables in Golang</title>
      <dc:creator>yanoandri</dc:creator>
      <pubDate>Wed, 05 Jan 2022 13:56:14 +0000</pubDate>
      <link>https://dev.to/yanoandri/playing-with-environment-variables-in-golang-3c2p</link>
      <guid>https://dev.to/yanoandri/playing-with-environment-variables-in-golang-3c2p</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Hi, in this session we will learn how to read variable keys from &lt;code&gt;.env&lt;/code&gt; file into our code, or we use to call it by handling environment variables in Golang.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hands On
&lt;/h2&gt;

&lt;p&gt;This will be a very quick tutorial, so let's just start it by initializing the project modules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go mod init {your package name}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then get and download specific dependencies from package &lt;code&gt;github.com/joho/godotenv&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go get github.com/joho/godotenv
go mod vendor
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's headed to the root directories of the project and created the file call &lt;code&gt;.env&lt;/code&gt; with contents of&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HELLO=from the other side
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and run our main script in &lt;code&gt;main.go&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "fmt"
    "log"
    "os"

    "github.com/joho/godotenv"
)

func init() {
    err := godotenv.Load(".env")
    if err != nil {
        log.Fatal("Error loading .env file")
    }
}

func main() {
    fmt.Printf("%s", os.Getenv("HELLO"))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or if we do not want to mix things up with &lt;code&gt;os.GetEnv&lt;/code&gt;, we can just also use it like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "fmt"
    "log"

    "github.com/joho/godotenv"
)

func main() {
    var envs map[string]string
    envs, err := godotenv.Read(".env")

    if err != nil {
        log.Fatal("Error loading .env file")
    }

    hello := envs["HELLO"]

    fmt.Printf("%s", hello)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;this will have the same results&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc7q05epwk66f4qrrb1iq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fc7q05epwk66f4qrrb1iq.png" alt="Results"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Allright, this is it for a quick tutorial, Happy exploring!&lt;/p&gt;

&lt;h2&gt;
  
  
  Source
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://zetcode.com/golang/env/" rel="noopener noreferrer"&gt;https://zetcode.com/golang/env/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/joho/godotenv" rel="noopener noreferrer"&gt;https://github.com/joho/godotenv&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>go</category>
      <category>webdev</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Database Handling with Golang Gorm (CRUD Handling)</title>
      <dc:creator>yanoandri</dc:creator>
      <pubDate>Mon, 27 Dec 2021 16:47:08 +0000</pubDate>
      <link>https://dev.to/yanoandri/database-handling-with-golang-gorm-crud-handling-4c66</link>
      <guid>https://dev.to/yanoandri/database-handling-with-golang-gorm-crud-handling-4c66</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Hi, in this session we will learn on how to use Gorm in Golang, to handle database operations such as create, read, update and delete (or usually called by many of us CRUD operations)&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Gorm?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://gorm.io/docs/" rel="noopener noreferrer"&gt;Gorm&lt;/a&gt; is just as many object relational mapper that every language / framework has, that handles database operations with defined models of our own tables inside our codes.  This post will only cover the basic connection, model definition, basic CRUD handling, and we will use postgresql as our database, so let's get start with it!&lt;/p&gt;

&lt;h2&gt;
  
  
  Initialize Package
&lt;/h2&gt;

&lt;p&gt;First we need to initiate our project with command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go mod init {your package name}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;after initializing the project, we can run the command to get the Gorm package and download it to our projects&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go get -u gorm.io/gorm
go mod vendor
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, so we will separate a folders for configuration, model definition and a main package for running this tutorial, here's my folder structured looks like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- config
 |_ config.go
- models
 |_ payment.go
- test.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Connecting to DB (Using PostgreSQL)
&lt;/h2&gt;

&lt;p&gt;the code inside &lt;code&gt;config.go&lt;/code&gt; is utilize for handling database connection&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package config

import (
    "fmt"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

const (
    Host     = "localhost"
    User     = "postgres"
    Password = "*******"
    Name     = "payment"
    Port     = "5432"
)

func Setup() (*gorm.DB, error) {
    connectionString := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable",
        Host,
        Port,
        User,
        Name,
        Password,
    )

    db, err := gorm.Open(postgres.Open(connectionString), &amp;amp;gorm.Config{})
    if err != nil {
        return nil, err
    }
    return db, nil
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;notice that in this file, we defined the connection with enum to handle host, database name, and user authentication needed to connect into our database, also since we use postgre database we import only for the postgres driver&lt;/p&gt;

&lt;p&gt;let's try our connection first in &lt;code&gt;test.go&lt;/code&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "errors"
    "fmt"
    "log"

    "github.com/yanoandri/simple-goorm/config"
    "gorm.io/gorm"
)

func main() {
    //connect to postgresql
    _, err := config.Setup()
    if err != nil {
        log.Panic(err)
        return
    }
    fmt.Println("Connected")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;if the credentials provided in &lt;code&gt;config.go&lt;/code&gt; are correctly provided, the program print "Connected" to mark our connection is successful.  For this part, we ignore the return value first, since we are going to talk about in the next part&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fluyogbyizg5m0jqm8ik7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fluyogbyizg5m0jqm8ik7.png" alt="Connected" width="123" height="49"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Model Definition
&lt;/h2&gt;

&lt;p&gt;Let's try creating our first model, we will define the &lt;code&gt;payment.go&lt;/code&gt; as our first table&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package models

import (
    "time"

    "github.com/google/uuid"
)

type Payment struct {
    ID          uuid.UUID `gorm:"type:uuid;default:uuid_generate_v4();primaryKey;"`
    PaymentCode string
    Name        string
    Status      string
    Created     time.Time `gorm:"autoCreateTime"`
    Updated     time.Time `gorm:"autoUpdateTime"`
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside the struct that we named as &lt;code&gt;payments&lt;/code&gt;, we defined the datatypes of every column inside it, you can see this &lt;a href="https://gorm.io/docs/models.html" rel="noopener noreferrer"&gt;docs&lt;/a&gt; on how to use it properly for your table definition&lt;/p&gt;

&lt;p&gt;We will try to migrate this table definition inside model into our database, let's use the successful return value of &lt;code&gt;gorm.DB&lt;/code&gt; in the earlier section and modify our &lt;code&gt;test.go&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "errors"
    "fmt"
    "log"

    "github.com/yanoandri/simple-goorm/config"
    "github.com/yanoandri/simple-goorm/models"
    "gorm.io/gorm"
)

func main() {
    //connect to postgresql
    db, err := config.Setup()
    if err != nil {
        log.Panic(err)
        return
    }
    fmt.Println("Connected")
    //migrate models inside project
    db.AutoMigrate(models.Payment{})
    fmt.Println("Migrated")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice the &lt;code&gt;db.AutoMigrate&lt;/code&gt; function is use to call the migration if there are any change inside &lt;code&gt;models&lt;/code&gt; folder, if there are nothing to change, then it will not make any changes into it&lt;/p&gt;

&lt;h2&gt;
  
  
  CRUD Handling
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Create
&lt;/h3&gt;

&lt;p&gt;Let's try to cover create part this time, we will make the &lt;code&gt;CreatePayment&lt;/code&gt; function outside the main function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func CreatePayment(db *gorm.DB, payment models.Payment) (int64, error) {
    result := db.Create(&amp;amp;payment)
    if result.RowsAffected == 0 {
        return 0, errors.New("payment not created")
    }
    return result.RowsAffected, nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;then run it inside our &lt;code&gt;main&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    //connect to postgresql
    db, err := config.Setup()
    if err != nil {
        log.Panic(err)
        return
    }
    fmt.Println("Connected")

    // create a payment
    payment := models.Payment{
        PaymentCode: "XXX-1",
        Name:        "Payment for item #1",
        Status:      "PENDING",
    }

    result, err := CreatePayment(db, payment)
    if err != nil {
        log.Panic(err)
        return
    }
    fmt.Println("Payment created", result)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;results in our database&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4qf170655ylk8lqrvtv3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4qf170655ylk8lqrvtv3.png" alt="Create results" width="800" height="68"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Select with id
&lt;/h3&gt;

&lt;p&gt;In earlier create function, we only return the number of rows that we created.  This time we return the model as a struct&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func SelectPaymentWIthId(db *gorm.DB, id string) (models.Payment, error) {
    var payment models.Payment
    result := db.First(&amp;amp;payment, "id = ?", id)
    if result.RowsAffected == 0 {
        return models.Payment{}, errors.New("payment data not found")
    }
    return payment, nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in &lt;code&gt;test.go&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    //connect to postgresql
    db, err := config.Setup()
    if err != nil {
        log.Panic(err)
        return
    }
    fmt.Println("Connected")

    // select a payment
    var id string
    fmt.Println("Input payment id : ")
    fmt.Scanln(&amp;amp;id)

    payment, _ := SelectPaymentWIthId(db, id)
    fmt.Println("Your payment is", payment)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;results&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff5j19ju2gsbaicgeufm6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff5j19ju2gsbaicgeufm6.png" alt="Selected" width="800" height="69"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;h3&gt;
  
  
  Update
&lt;/h3&gt;

&lt;p&gt;This time we will update the mark the status as &lt;code&gt;PAID&lt;/code&gt; for the specific record&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func UpdatePayment(db *gorm.DB, id string, payment models.Payment) (models.Payment, error) {
    var updatePayment models.Payment
    result := db.Model(&amp;amp;updatePayment).Where("id = ?", id).Updates(payment)
    if result.RowsAffected == 0 {
        return models.Payment{}, errors.New("payment data not update")
    }
    return updatePayment, nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in &lt;code&gt;test.go&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    //connect to postgresql
    db, err := config.Setup()
    if err != nil {
        log.Panic(err)
        return
    }
    fmt.Println("Connected")

    // select a payment
    var id string
    fmt.Println("Input payment id : ")
    fmt.Scanln(&amp;amp;id)

    payment, _ := SelectPaymentWIthId(db, id)
    fmt.Println("Your payment is", payment)

    // update a payment with previous id
    updatedPayment, _ := UpdatePayment(db, id, models.Payment{
        Status: "PAID",
    })
    fmt.Println("Your payment status now is ", updatedPayment)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;results&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzev9zqi4434vlk93cg4b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzev9zqi4434vlk93cg4b.png" alt="Updated" width="800" height="97"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;notice the only information that returned inside struct is only the updated attributes&lt;/p&gt;

&lt;h3&gt;
  
  
  Delete
&lt;/h3&gt;

&lt;p&gt;The last part is how to delete from tables&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func DeletePayment(db *gorm.DB, id string) (int64, error) {
    var deletedPayment models.Payment
    result := db.Where("id = ?", id).Delete(&amp;amp;deletedPayment)
    if result.RowsAffected == 0 {
        return 0, errors.New("payment data not update")
    }
    return result.RowsAffected, nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in &lt;code&gt;test.go&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    //connect to postgresql
    db, err := config.Setup()
    if err != nil {
        log.Panic(err)
        return
    }
    fmt.Println("Connected")

    // select a payment
    var id string
    fmt.Println("Input payment id : ")
    fmt.Scanln(&amp;amp;id)

    payment, _ := SelectPaymentWIthId(db, id)
    fmt.Println("Your payment is", payment)

    // delete a payment with previous id
    DeletePayment(db, id)
    fmt.Println("Your payment now is deleted")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;in our script&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyozj2guu9m3x42qmv36e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyozj2guu9m3x42qmv36e.png" alt="Results in script" width="800" height="77"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;let's see the results directly database&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6na7zapgouw4iu562i1u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6na7zapgouw4iu562i1u.png" alt="Results Deleted DB" width="800" height="107"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;That's it on how to handle CRUD and connection to database with Golang Gorm.  This is really based on my experience and there's still so much more to explore about this package. Happy exploring!&lt;/p&gt;

&lt;p&gt;Source :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://gorm.io/" rel="noopener noreferrer"&gt;Gorm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/yanoandri/simple-goorm" rel="noopener noreferrer"&gt;Full source&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>go</category>
      <category>tutorial</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Build a simple API with Golang echo framework</title>
      <dc:creator>yanoandri</dc:creator>
      <pubDate>Sun, 19 Dec 2021 15:06:59 +0000</pubDate>
      <link>https://dev.to/yanoandri/build-a-simple-api-with-golang-echo-framework-320g</link>
      <guid>https://dev.to/yanoandri/build-a-simple-api-with-golang-echo-framework-320g</guid>
      <description>&lt;p&gt;Hi everyone, in this article i'm going to show tutorial on how to create simple API with Echo Golang framework&lt;/p&gt;

&lt;p&gt;First thing that we need to do is to create project in golang by running this command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go mod init {your-package name}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go mod init github.com/yanoandri/simple-golang-echo
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;your package name could be anything, but for this tutorial i'm using the url of my github repos for later&lt;/p&gt;

&lt;p&gt;after running the command, there will be a file call &lt;code&gt;go.mod&lt;/code&gt; and this time we will run this command to get echo dependencies&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go get github.com/labstack/echo/v4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and copy the downloaded dependencies to our project's folder that we are going to call &lt;code&gt;vendor&lt;/code&gt; with command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go mod vendor
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;after the dependency is downloaded, let's start to create a file call &lt;code&gt;server.go&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "net/http"

    "github.com/labstack/echo"
)

type HelloWorld struct {
    Message string `json:"message"`
}

func main() {
    e := echo.New()
    e.GET("/hello", Greetings)
    e.Logger.Fatal(e.Start(":3000"))
}

func Greetings(c echo.Context) error {
    return c.JSON(http.StatusOK, HelloWorld{
        Message: "Hello World",
    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;let's run the API that we just created, by command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;go run server.go
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwwjn62onrsos9xbdvfuv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwwjn62onrsos9xbdvfuv.png" alt="Successfully run echo" width="367" height="202"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then we will test the API by request to &lt;code&gt;http://localhost:3000/hello&lt;/code&gt; the response will be&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{"message":"Hello World"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's head back and handle any parameters or query inside the url, by modifying some of the line in the main function. let's add the function to handle query and parameters&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func GreetingsWithParams(c echo.Context) error {
    params := c.Param("name")
    return c.JSON(http.StatusOK, HelloWorld{
        Message: "Hello World, my name is " + params,
    })
}

func GreetingsWithQuery(c echo.Context) error {
    query := c.QueryParam("name")
    return c.JSON(http.StatusOK, HelloWorld{
        Message: "Hello World i'm using queries and my name is " + query,
    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then in the &lt;code&gt;main&lt;/code&gt; function, add this two line&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;e.GET("/hello/:name", GreetingsWithParams)
e.GET("/hello-queries", GreetingsWithQuery)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;let's test it again by requesting the url with parameters&lt;br&gt;
&lt;code&gt;localhost:3000/hello/yano&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{"message":"Hello World, my name is yano"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and the second request using query with &lt;code&gt;http://localhost:3000/hello-queries?name=yano&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{"message":"Hello World i'm using queries and my name is yano"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's it for this tutorial, thank you for reading and happy coding :)&lt;/p&gt;

&lt;p&gt;Source:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://echo.labstack.com/guide/" rel="noopener noreferrer"&gt;Echo&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/yanoandri/simple-golang-echo" rel="noopener noreferrer"&gt;Repo&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>go</category>
      <category>beginners</category>
      <category>tutorial</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
