Go sql layer architecture sample

go-sql-rest-api-template

To run the application

go run main.go

API Design

Common HTTP methods

  • GET: retrieve a representation of the resource
  • POST: create a new resource
  • PUT: update the resource
  • PATCH: perform a partial update of a resource
  • DELETE: delete a resource

API design for health check

To check if the service is available.

Request: GET /health

Response:

{
    "status": "UP",
    "details": {
        "sql": {
            "status": "UP"
        }
    }
}

API design for users

Resource: users

Get all users

Request: GET /users

Response:

[
    {
        "id": "spiderman",
        "username": "peter.parker",
        "email": "[email protected]",
        "phone": "0987654321",
        "dateOfBirth": "1962-08-25T16:59:59.999Z"
    },
    {
        "id": "wolverine",
        "username": "james.howlett",
        "email": "[email protected]",
        "phone": "0987654321",
        "dateOfBirth": "1974-11-16T16:59:59.999Z"
    }
]

Get one user by id

Request: GET /users/:id

GET /users/wolverine

Response:

{
    "id": "wolverine",
    "username": "james.howlett",
    "email": "[email protected]",
    "phone": "0987654321",
    "dateOfBirth": "1974-11-16T16:59:59.999Z"
}

Create a new user

Request: POST /users

{
    "id": "wolverine",
    "username": "james.howlett",
    "email": "[email protected]",
    "phone": "0987654321",
    "dateOfBirth": "1974-11-16T16:59:59.999Z"
}

Response: 1: success, 0: duplicate key, -1: error

1

Update one user by id

Request: PUT /users/:id

PUT /users/wolverine
{
    "username": "james.howlett",
    "email": "[email protected]",
    "phone": "0987654321",
    "dateOfBirth": "1974-11-16T16:59:59.999Z"
}

Response: 1: success, 0: not found, -1: error

1

Delete a new user by id

Request: DELETE /users/:id

DELETE /users/wolverine

Response: 1: success, 0: not found, -1: error

1

Common libraries

  • core-go/health: include HealthHandler, HealthChecker, SqlHealthChecker
  • core-go/config: to load the config file, and merge with other environments (SIT, UAT, ENV)
  • core-go/log: log and log middleware

core-go/health

To check if the service is available, refer to core-go/health

Request: GET /health

Response:

{
    "status": "UP",
    "details": {
        "sql": {
            "status": "UP"
        }
    }
}

To create health checker, and health handler

    db, err := sql.Open(conf.Driver, conf.DataSourceName)
    if err != nil {
        return nil, err
    }

    sqlChecker := s.NewSqlHealthChecker(db)
    healthHandler := health.NewHealthHandler(sqlChecker)

To handler routing

    r := mux.NewRouter()
    r.HandleFunc("/health", healthHandler.Check).Methods("GET")

core-go/config

To load the config from "config.yml", in "configs" folder

package main

import "github.com/core-go/config"

type Root struct {
    DB DatabaseConfig `mapstructure:"db"`
}

type DatabaseConfig struct {
    Driver         string `mapstructure:"driver"`
    DataSourceName string `mapstructure:"data_source_name"`
}

func main() {
    var conf Root
    err := config.Load(&conf, "configs/config")
    if err != nil {
        panic(err)
    }
}

core-go/log & core-go/middleware

import (
    "github.com/core-go/config"
    "github.com/core-go/log"
    m "github.com/core-go/middleware"
    "github.com/gorilla/mux"
)

func main() {
    var conf app.Root
    config.Load(&conf, "configs/config")

    r := mux.NewRouter()

    log.Initialize(conf.Log)
    r.Use(m.BuildContext)
    logger := m.NewStructuredLogger()
    r.Use(m.Logger(conf.MiddleWare, log.InfoFields, logger))
    r.Use(m.Recover(log.ErrorMsg))
}

To configure to ignore the health check, use "skips":

middleware:
  skips: /health
Similar Resources

Elastic Stack Docker + Sample Go AppElastic Stack Docker + Sample Go App

Elastic Stack Docker + Sample Go AppElastic Stack Docker + Sample Go App

📶 Elastic Stack Docker + Sample Go App Test Elastic Stack which includes Elasticsearch, Kibana, Filebeat and Metricbeat. It comes with a very simple

Jan 14, 2022

EdgeDB-Golang-Docker-Sample - The sample of connection between EdgeDB Server and Go Echo API Server

EdgeDB Golang Docker Sample 『Go + Docker Composeを使ってEdgeDBを動かしてみた』のサンプルコードです。 使い

Nov 2, 2022

Sample code snippet to familiarize golang . Concept of goroutines , channels, concurrency is implemented in a sample scenario

go-mysql-goroutines-channel Sample code snippet to familiarize golang . Concept of goroutines , channels, concurrency , interface, slice, error handli

May 29, 2022

Sample Go REST API implementation with DDD using Clean Architecture.

This layer is a part developed for client-side (mobile, web, etc.) applications to access our domain. It will forward the requests from this layer to the application layer and expose the response it receives from the application layer.

Jan 3, 2023

This is demo / sample / example project using microservices architecture for Online Food Delivery App.

Microservices This is demo / sample / example project using microservices architecture for Online Food Delivery App. Architecture Services menu-servic

Nov 21, 2022

A sample web API in GO (with GIn) under a domain driven architecture.

Golang Sample API Domain Driven Design Pattern 1. About This sample project presents a custom made domain driven API architecture in Golang using the

Jan 10, 2022

Implement clean-architecture sample by golang

Implement clean-architecture sample by golang

Feb 17, 2022

Microservice - A sample architecture of a microservice in go

#microservice Folder structure required. service certs config config.yaml loggin

Feb 3, 2022

Go (Golang) Clean Architecture based on Reading Uncle Bob's Clean Architecture

Go (Golang) Clean Architecture based on Reading Uncle Bob's Clean Architecture

go-clean-arch Changelog v1: checkout to the v1 branch Proposed on 2017, archived to v1 branch on 2018 Desc: Initial proposal by me. The story can be r

Jan 1, 2023

Golang Clean Architecture based on Uncle Bob's Clean Architecture and Summer internship in 2021

clean-architecture-api Description This is an example of implemention of Clean Architecture in Golang projects. This project has 4 layer : Infrastruct

Feb 20, 2022

Hexagonal architecture paradigms, such as dividing adapters into primary (driver) and secondary (driven)Hexagonal architecture paradigms, such as dividing adapters into primary (driver) and secondary (driven)

authorizer Architecture In this project, I tried to apply hexagonal architecture paradigms, such as dividing adapters into primary (driver) and second

Dec 7, 2021

This is a POC (Proof of Concept) using Hexagonal Architecture, SOLID, DDD, Clean Code, Clean Architecture

This is a POC (Proof of Concept) using Hexagonal Architecture, SOLID, DDD, Clean Code, Clean Architecture

Projeto Planetas Star Wars: Esse projeto de trata de uma POC utilizando os conceitos de Clean Arch, Hexagonal Arch, Clean Code, DDD, e SOLID. O princi

Feb 10, 2022

Database Abstraction Layer (dbal) for Go. Support SQL builder and get result easily (now only support mysql)

godbal Database Abstraction Layer (dbal) for go (now only support mysql) Motivation I wanted a DBAL that No ORM、No Reflect、Concurrency Save, support S

Nov 17, 2022

A course to build the SQL layer of a distributed database.

TinySQL TinySQL is a course designed to teach you how to implement a distributed relational database in Go. TinySQL is also the name of the simplifed

Jan 8, 2023

Golang REST Layer SQL Storage Handler

This REST Layer resource storage backend stores data in a SQL Database using database/sql.

Feb 15, 2022

Go sql modular sample

go-sql-rest-api To run the application go run main.go API Design Common HTTP methods GET: retrieve a representation of the resource POST: create a new

Mar 12, 2022

Command line tool to generate idiomatic Go code for SQL databases supporting PostgreSQL, MySQL, SQLite, Oracle, and Microsoft SQL Server

About xo xo is a command-line tool to generate Go code based on a database schema or a custom query. xo works by using database metadata and SQL intro

Jan 8, 2023

Go tool for generating sql scanners, sql statements and other helper functions

sqlgen generates SQL statements and database helper functions from your Go structs. It can be used in place of a simple ORM or hand-written SQL. See t

Nov 24, 2022

A logger for Go SQL database driver without modify existing *sql.DB stdlib usage.

A logger for Go SQL database driver without modify existing *sql.DB stdlib usage.

SQLDB-Logger A logger for Go SQL database driver without modify existing *sql.DB stdlib usage. Colored console writer output above only for sample/dev

Jan 3, 2023
Compose sample application Go server with an Nginx proxy and a Postgres database

Compose sample application Go server with an Nginx proxy and a Postgres database Project

Apr 7, 2022
A sample url shortener app to test Keploy integration capabilities
A sample url shortener app to test Keploy integration capabilities

Example URL Shortener A sample url shortener app to test Keploy integration capabilities Installation git clone https://github.com/keploy/example-url-

Oct 22, 2022
GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework
GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework

GoCondor is a golang web framework with an MVC like architecture, it's based on Gin framework, it features a simple organized directory structure for your next project with a pleasant development experience, made for developing modern APIs and microservices.

Dec 29, 2022
The source code for workshop Scalable architecture using Redis as backend database using Golang + Redis

The source code for workshop Scalable architecture using Redis as backend database using Golang + Redis

Sep 23, 2022
Clean Architecture template for Golang services
Clean Architecture template for Golang services

Go Clean template Clean Architecture template for Golang services Overview The purpose of the template is to show: how to organize a project and preve

Oct 19, 2022
Implementation of clean architecture in golang with gin-gonic & gorm

Boilerplate API Boilerplate API template includes all the common packages and setup used for API development in this Company. Development Copy .env.ex

Feb 15, 2022
Clean Architecture using Golang with Gin framework

Clean Architecture using Golang with Gin framework Template Structure Gin is a web framework written in Go (Golang). It features a martini-like API wi

Dec 16, 2022
GraphJin - Build APIs in 5 minutes with GraphQL. An instant GraphQL to SQL compiler.
GraphJin - Build APIs in 5 minutes with GraphQL. An instant GraphQL to SQL compiler.

GraphJin gives you a high performance GraphQL API without you having to write any code. GraphQL is automagically compiled into an efficient SQL query. Use it either as a library or a standalone service.

Dec 29, 2022
Golang Event Scheduling Sample Using Postgresql Database as persisting layer.

Database Based Event Scheduling Example that demonstrates super basic database based event scheduling. To run this example; Copy .env.example to .env

Nov 28, 2022
Onion-Layer-Golang - A web application boilerplate built with go and clean architecture
Onion-Layer-Golang - A web application boilerplate built with go and clean architecture

go-clean-architecture-web-application-boilerplate A web application boilerplate

May 4, 2022