Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Golang] Using Repository Pattern to integrate the Database (Postgres)

Posted on March 6, 2022March 10, 2022 By nim No Comments on [Golang] Using Repository Pattern to integrate the Database (Postgres)

Nim đã có 1 post thiết kế sường cho 1 project golang!
Giờ chúng ta là rõ việc làm sao để golang tương tác được với Database và ở đây là postgres
Chúng ta tiếp tục mục repository của bài viết sau:

[Golang] Chuẩn bị 1 project golang.

Contents

Toggle
  • 1) Install and practise the migration DB with Golang
    • 1.1) Install
    • 1.2) design sql file
    • 1.3) declare db config and pratice
  • 2) Repository to manage the DB with Golang
    • 2.1) db/db.go
    • 2.2) repository/voucher_repo.go
    • 2.3) model/hunter.go
    • 2.4)repository/repo_impl/voucher_repo_impl.go
  • 3) Config handler
  • 4) Config main.go

1) Install and practise the migration DB with Golang

Chúng ta sẽ sử dụng sql-migrate để thực hiện tạo table hoặc insert data vào database.
Và chúng ta sử dụng package sau:
https://github.com/rubenv/sql-migrate

1.1) Install

chạy command sau:

```bash
go get -v github.com/rubenv/sql-migrate/...
```

Test lại bằng command help nếu như dưới anh là ngon
sql-migrate --help

1.2) design sql file

Bạn tạo 1 thư mục migration và tạo 1 file sql như hình bên dưới

1.3) declare db config and pratice

Các cú pháp tạo table khá quen thuộc hi.
Cần chú ý 2 chỗ:
-- +migrate Up: là các Câu lệnh tạo bảng hay insert data
-- +migrate Down: Chúng ta anh để câu lệnh drop table

Tạo file config dbconfig.yml

development:
  dialect: postgres
  datasource: host=localhost port=5432 user=guru password=123456 dbname=timewise sslmode=disable
  dir: migrations
  table: migrations

production:
  dialect: postgres
  datasource: host=localhost port=5432 user=guru password=123456 dbname=timewise sslmode=disable
  dir: migrations
  table: migrations

Giải thích nhanh:
+ development: cái này để phân định config này thuộc môi trường nào, tý sẽ thấy phần command line
+ dialect: postgres : sử dụng database j?
+ datasource: host=localhost port=5432 user=guru password=123456 dbname=timewise sslmode=disable
-> đường dẫn khai báo kết nối đến database
+ dir: migrations: thự mục chứa các files .sql
+ table: migrations: nó tạo table tên là migrations trong database và ghi lại history migration.

Giờ thực hiện gõ comand tạo table
sql-migrate up -config="dbconfig.yml" -env="development"

Nếu như ảnh là có vẻ ngon
Kiểm tra database thấy đã tạo table

Muốn xoá table thì cũng dễ gõ:
sql-migrate down -config="dbconfig.yml" -env="development"

Ở trong thư mục migration bạn có thể tạo nhiều files sql
– 1_init.sql
– 2_wow.sql
các file sẽ được run từ 1 đến 2 -> n

chúng ta khám phá thêm bảng migration có j?

2) Repository to manage the DB with Golang

Bạn sẽ tham khảo giúp mình bài load config file trong golang đã nhé!

[Golang] Design config file or environment file with Golang

2.1) db/db.go

Chúng ta sử dụng các thư viện sau:
https://github.com/jmoiron/sqlx
trong thư mục db mình tạo file

2.2) repository/voucher_repo.go

Các bạn làm theo như ảnh:

Handler gửi các data (user or product) nhờ repository truy vấn xuống database và trả kết quả về handler.

Đâu tiên là thành phần interface:
Nó sẽ chưa các method để tương tác với các table trong database.

2.3) model/hunter.go

Model thì chưa fields đại diện cho các table mà chúng ta đang làm việc
hunter model.Hunter là ntn?

Khi chúng ta sự dụng mode này cho repository(database) thì cần chú ý

db:”hunter_id, omitempty”`

2.4)repository/repo_impl/voucher_repo_impl.go

Lúc đó thì repository_implement nhận biết tag_db “hunter_id” lấy giá trị từ value: HunterId và đưa nó đúng vào column hunter_id trong DB

repo_implement nó sẽ implement cái interface repository và nó chưa các code làm việc trực tiếp mới database.
Ở đây mình viết tạm 1 file implement đơn giản:

3) Config handler

Handler sẽ gọi sang repository

Chúng ta cần thêm vào struct như trên.

4) Config main.go

Giờ thực kiên tạo kết nối với DB ngay ở file main.

Bạn cần chú ý các phần mà mình gach
Golang

Post navigation

Previous Post: [Golang] Design config file or environment file with Golang
Next Post: [Golang] Convert this data type to another data type in Golang

More Related Articles

[Golang] Create multiple CRON functions by looping through a list Golang
[Golang] How do you read each line inside a file? Golang
[Golang/Redis/Riot] Redis migration from old to new infrastructure. AWS - Amazon Web Service
[Selenium] Save cookies of any website that is running on Selenium. Golang
[Golang] Thiết kế model trong golang và echo framework. Golang
[Golang] Writing a metrics exporter through Golang and Prometheus Golang

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Azure/Loadbalancer] Creating an internal load balancer on Azure Kubernetes Service (AKS). May 13, 2025
  • [Azure] The subscription is not registered to use namespace ‘Microsoft.ContainerService’ May 8, 2025
  • [Azure] Insufficient regional vcpu quota left May 8, 2025
  • [WordPress] How to add a Dynamic watermark on WordPress. May 6, 2025
  • [vnet/Azure] VNet provisioning via Terraform. April 28, 2025

Archives

  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.