• Stars
    star
    3,900
  • Rank 11,226 (Top 0.3 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created almost 2 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Go (Golang) Backend Clean Architecture project with Gin, MongoDB, JWT Authentication Middleware, Test, and Docker.

Go Backend Clean Architecture

A Go (Golang) Backend Clean Architecture project with Gin, MongoDB, JWT Authentication Middleware, Test, and Docker.

Go Backend Clean Architecture

You can use this project as a template to build your Backend project in the Go language on top of this project.

Before creating this project, I have gone through more than 20 projects related to the Go(Golang) Clean Architecture on GitHub.

Thanks to all those projects, I learned a lot from all of those. As I keep saying:

The best way to learn to code is to code. But, to write good code, you will also have to read good code. Make a habit of reading good code. You can find many open-source projects on GitHub and start reading.

Then for the implementation part, I combined all of my ideas, experiences, and learnings from those projects to create this project.

And as always I would love to get feedback on my project. This helps everyone and most importantly me.

Learn about this project architecture in detail from the blogs mentioned below:

Architecture Layers of the project

  • Router
  • Controller
  • Usecase
  • Repository
  • Domain

Go Backend Clean Architecture Diagram

About me

Hi, I am Amit Shekhar, I have mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

You can connect with me on:

System Design Playlist on YouTube

Major Packages used in this project

  • gin: Gin is an HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need a smashing performance, get yourself some Gin.
  • mongo go driver: The Official Golang driver for MongoDB.
  • jwt: JSON Web Tokens are an open, industry-standard RFC 7519 method for representing claims securely between two parties. Used for Access Token and Refresh Token.
  • viper: For loading configuration from the .env file. Go configuration with fangs. Find, load, and unmarshal a configuration file in JSON, TOML, YAML, HCL, INI, envfile, or Java properties formats.
  • bcrypt: Package bcrypt implements Provos and MaziΓ¨res's bcrypt adaptive hashing algorithm.
  • testify: A toolkit with common assertions and mocks that plays nicely with the standard library.
  • mockery: A mock code autogenerator for Golang used in testing.
  • Check more packages in go.mod.

Public API Request Flow without JWT Authentication Middleware

Public API Request Flow

Private API Request Flow with JWT Authentication Middleware

JWT Authentication Middleware for Access Token Validation.

Private API Request Flow

How to run this project?

We can run this Go Backend Clean Architecture project with or without Docker. Here, I am providing both ways to run this project.

  • Clone this project
# Move to your workspace
cd your-workspace

# Clone this project into your workspace
git clone https://github.com/amitshekhariitbhu/go-backend-clean-architecture.git

# Move to the project root directory
cd go-backend-clean-architecture

Run without Docker

  • Create a file .env similar to .env.example at the root directory with your configuration.
  • Install go if not installed on your machine.
  • Install MongoDB if not installed on your machine.
  • Important: Change the DB_HOST to localhost (DB_HOST=localhost) in .env configuration file. DB_HOST=mongodb is needed only when you run with Docker.
  • Run go run cmd/main.go.
  • Access API using http://localhost:8080

Run with Docker

  • Create a file .env similar to .env.example at the root directory with your configuration.
  • Install Docker and Docker Compose.
  • Run docker-compose up -d.
  • Access API using http://localhost:8080

How to run the test?

# Run all tests
go test ./...

How to generate the mock code?

In this project, to test, we need to generate mock code for the use-case, repository, and database.

# Generate mock code for the usecase and repository
mockery --dir=domain --output=domain/mocks --outpkg=mocks --all

# Generate mock code for the database
mockery --dir=mongo --output=mongo/mocks --outpkg=mocks --all

Whenever you make changes in the interfaces of these use-cases, repositories, or databases, you need to run the corresponding command to regenerate the mock code for testing.

The Complete Project Folder Structure

.
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ api
β”‚   β”œβ”€β”€ controller
β”‚   β”‚   β”œβ”€β”€ login_controller.go
β”‚   β”‚   β”œβ”€β”€ profile_controller.go
β”‚   β”‚   β”œβ”€β”€ profile_controller_test.go
β”‚   β”‚   β”œβ”€β”€ refresh_token_controller.go
β”‚   β”‚   β”œβ”€β”€ signup_controller.go
β”‚   β”‚   └── task_controller.go
β”‚   β”œβ”€β”€ middleware
β”‚   β”‚   └── jwt_auth_middleware.go
β”‚   └── route
β”‚       β”œβ”€β”€ login_route.go
β”‚       β”œβ”€β”€ profile_route.go
β”‚       β”œβ”€β”€ refresh_token_route.go
β”‚       β”œβ”€β”€ route.go
β”‚       β”œβ”€β”€ signup_route.go
β”‚       └── task_route.go
β”œβ”€β”€ bootstrap
β”‚   β”œβ”€β”€ app.go
β”‚   β”œβ”€β”€ database.go
β”‚   └── env.go
β”œβ”€β”€ cmd
β”‚   └── main.go
β”œβ”€β”€ docker-compose.yaml
β”œβ”€β”€ domain
β”‚   β”œβ”€β”€ error_response.go
β”‚   β”œβ”€β”€ jwt_custom.go
β”‚   β”œβ”€β”€ login.go
β”‚   β”œβ”€β”€ profile.go
β”‚   β”œβ”€β”€ refresh_token.go
β”‚   β”œβ”€β”€ signup.go
β”‚   β”œβ”€β”€ success_response.go
β”‚   β”œβ”€β”€ task.go
β”‚   └── user.go
β”œβ”€β”€ go.mod
β”œβ”€β”€ go.sum
β”œβ”€β”€ internal
β”‚   └── tokenutil
β”‚       └── tokenutil.go
β”œβ”€β”€ mongo
β”‚   └── mongo.go
β”œβ”€β”€ repository
β”‚   β”œβ”€β”€ task_repository.go
β”‚   β”œβ”€β”€ user_repository.go
β”‚   └── user_repository_test.go
└── usecase
    β”œβ”€β”€ login_usecase.go
    β”œβ”€β”€ profile_usecase.go
    β”œβ”€β”€ refresh_token_usecase.go
    β”œβ”€β”€ signup_usecase.go
    β”œβ”€β”€ task_usecase.go
    └── task_usecase_test.go

API documentation of Go Backend Clean Architecture

View API Doc Button

Example API Request and Response

  • signup

    • Request
    curl --location --request POST 'http://localhost:8080/signup' \
    --data-urlencode '[email protected]' \
    --data-urlencode 'password=test' \
    --data-urlencode 'name=Test Name'
    
    • Response
    {
      "accessToken": "access_token",
      "refreshToken": "refresh_token"
    }
  • login

    • Request
    curl --location --request POST 'http://localhost:8080/login' \
    --data-urlencode '[email protected]' \
    --data-urlencode 'password=test'
    
    • Response
    {
      "accessToken": "access_token",
      "refreshToken": "refresh_token"
    }
  • profile

    • Request
    curl --location --request GET 'http://localhost:8080/profile' \
    --header 'Authorization: Bearer access_token'
    
    • Response
    {
      "name": "Test Name",
      "email": "[email protected]"
    }
  • task create

    • Request
    curl --location --request POST 'http://localhost:8080/task' \
    --header 'Authorization: Bearer access_token' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode 'title=Test Task'
    
    • Response
    {
      "message": "Task created successfully"
    }
  • task fetch

    • Request
    curl --location --request GET 'http://localhost:8080/task' \
    --header 'Authorization: Bearer access_token'
    
    • Response
    [
      {
        "title": "Test Task"
      },
      {
        "title": "Test Another Task"
      }
    ]
  • refresh token

    • Request
    curl --location --request POST 'http://localhost:8080/refresh' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode 'refreshToken=refresh_token'
    
    • Response
    {
      "accessToken": "access_token",
      "refreshToken": "refresh_token"
    }

TODO

  • Improvement based on feedback.
  • Add more test cases.
  • Always try to update with the latest version of the packages used.

If this project helps you in anyway, show your love ❀️ by putting a ⭐ on this project ✌️

License

   Copyright (C) 2023 Amit Shekhar

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Contributing to Go Backend Clean Architecture

All pull requests are welcome.

More Repositories

1

android-interview-questions

Your Cheat Sheet For Android Interview - Android Interview Questions and Answers
Java
11,105
star
2

Android-Debug-Database

A library for debugging android databases and shared preferences - Make Debugging Great Again
Java
8,383
star
3

from-java-to-kotlin

From Java To Kotlin - Your Cheat Sheet For Java To Kotlin
Java
6,163
star
4

Fast-Android-Networking

πŸš€ A Complete Fast Android Networking Library that also supports HTTP/2 πŸš€
Java
5,662
star
5

RxJava2-Android-Samples

RxJava 2 Android Examples - How to use RxJava 2 in Android
Java
4,960
star
6

PRDownloader

PRDownloader - A file downloader library for Android with pause and resume support
Java
3,231
star
7

awesome-android-complete-reference

Here I list down all of the high-quality blogs that I publish on my website.
Java
2,831
star
8

android-developer-roadmap

Android Developer Roadmap - A complete roadmap to learn Android App Development
Java
2,754
star
9

ridesharing-uber-lyft-app

Ride-Sharing Uber Lyft Android App - Learn to build a ride-sharing Android Taxi Clone App like Uber, Lyft - Open-Source Project
Kotlin
1,481
star
10

AndroidTensorFlowMachineLearningExample

Android TensorFlow MachineLearning Example (Building TensorFlow for Android)
Java
1,432
star
11

Kotlin-Coroutines-Android-Examples

Moved to https://github.com/amitshekhariitbhu/Learn-Kotlin-Coroutines
1,023
star
12

awesome-android-things

A curated list of awesome android things tutorials, libraries and much more at one place
Java
960
star
13

Android-TensorFlow-Lite-Example

Android TensorFlow Lite Machine Learning Example
Java
745
star
14

iOS-Viper-Architecture

This repository contains a detailed sample app that implements VIPER architecture in iOS using libraries and frameworks like Alamofire, AlamofireImage, PKHUD, CoreData etc.
Swift
716
star
15

FlatBuffer

FlatBuffer : Android Sample Application
Java
615
star
16

GlideBitmapPool

Glide Bitmap Pool is a memory management library for reusing the bitmap memory
Java
588
star
17

MVVM-Architecture-Android

MVVM architecture using Kotlin, Dagger, Retrofit, Coroutines, Flow, StateFlow, and etc.
Kotlin
545
star
18

AndroidTensorFlowMNISTExample

Android TensorFlow MachineLearning MNIST Example (Building Model with TensorFlow for Android)
Java
462
star
19

Learn-Kotlin-Flow

Learn Kotlin Flow by real examples for Android
Kotlin
400
star
20

Learn-Kotlin-Coroutines

Learn Kotlin Coroutines by real examples for Android
Kotlin
345
star
21

RxJava3-Android-Examples

RxJava 3 Android Examples - Migration From RxJava 2 to RxJava 3 - How to use RxJava 3 in Android
Kotlin
287
star
22

NYBus

NYBus (RxBus) - A pub-sub library for Android and Java applications
Java
285
star
23

Android-MVP-Sample-Application

Android MVP Sample Application
Java
259
star
24

SnapHelperExample

SnapHelper Example for Android Application
Java
248
star
25

best-android-tutorials

Best Free Android Tutorials
156
star
26

android-mvp-basic-sample

Android MVP Basic Sample
Java
148
star
27

RxJavaPriorityScheduler

RxPS - RxJavaPriorityScheduler - A RxJava Priority Scheduler library for Android and Java applications
Java
143
star
28

Kotlin-Networking

Kotlin Networking - An elegant networking library written in Kotlin
Kotlin
98
star
29

Android-Shimmer-Example

An example project to demonstrate how to use Shimmer in your Android application
Kotlin
61
star
30

AppLock

Android Application for app lock
Java
39
star
31

android-online-course

Android Online Course
23
star
32

Android-HotFix

Android HotFix Library For On The Fly Bug Fix. Bug fix without updating APK.
Java
23
star
33

Floatingview

Java
8
star
34

WordSuggestions

WordSuggestions
C++
2
star
35

amitshekhariitbhu

A repository to add a README.md to my GitHub profile
1
star