• Stars
    star
    224
  • Rank 177,792 (Top 4 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

UGin is an API boilerplate written in Go (Golang) with Gin Framework.

UGin - Ultimate Gin API

UGin is an API boilerplate written in Go (Golang) with Gin Framework. https://github.com/gin-gonic/gin

Database Support

UGin uses gorm as an ORM. So Sqlite3, MySQL and PostgreSQL is supported. You just need to edit config.yml file according to your setup.

config.yml content:

database:
  driver: "postgres"
  dbname: "ugin"
  username: "user"
  password: "password"
  host: "localhost"
  port: "5432"

Default Models

UGin has two models (Post and Tag) as boilerplate to show relational database usage.

/model/post-model.go content:

type Post struct {
	gorm.Model
	Name        string `json:"Name" gorm:"type:varchar(255)"`
	Description string `json:"Description"  gorm:"type:text"`
	Tags        []Tag  // One-To-Many relationship (has many - use Tag's UserID as foreign key)
}

type Tag struct {
	gorm.Model
	PostID      uint   `gorm:"index"` // Foreign key (belongs to)
	Name        string `json:"Name" gorm:"type:varchar(255)"`
	Description string `json:"Description" gorm:"type:text"`
}

Filtering, Search and Pagination

UGin has it's own filtering, search and pagination system. You just need to use these parameters.

Query parameters:

/posts/?Limit=2
/posts/?Offset=0
/posts/?Sort=ID
/posts/?Order=DESC
/posts/?Search=hello

Full: http://localhost:8081/posts/?Limit=25&Offset=0&Sort=ID&Order=DESC&Search=hello

Running

To run UGin with Docker, firstly build an image:

make build-image

To run Ugin with MySQL:

make run-app-mysql

To run Ugin with PostgreSQL:

make run-app-postgres

Application will be served at ":8081"

Logging

UGin has a very powerful logging logic. There is application log (ugin.log), database log (ugin.db.log) and access log (ugin.access.log)

ugin.log:

INFO 2021-09-19T00:33:32+03:00 Server is starting at 127.0.0.1:8081
ERROR 2021-09-19T00:39:19+03:00 Failed to open log file ugin.log

ugin.db.log:

2021/09/19 00:33:32 /home/user/projects/ugin/pkg/database/database.go:76
[0.023ms] [rows:-] SELECT * FROM `posts` LIMIT 1

2021/09/19 00:33:32 /home/user/go/pkg/mod/gorm.io/driver/[email protected]/migrator.go:261
[0.015ms] [rows:-] SELECT count(*) FROM sqlite_master WHERE type = "index" AND tbl_name = "posts" AND name = "idx_posts_deleted_at"

2021/09/19 00:33:32 /home/user/go/pkg/mod/gorm.io/driver/[email protected]/migrator.go:32
[0.010ms] [rows:-] SELECT count(*) FROM sqlite_master WHERE type='table' AND name="tags"

2021/09/19 00:33:32 /home/user/projects/ugin/pkg/database/database.go:76
[0.011ms] [rows:-] SELECT * FROM `tags` LIMIT 1

ugin.access.log:

[GIN] 2021/09/19 - 00:33:43 | 200 |    9.255625ms |       127.0.0.1 | GET      "/posts/"
[GIN] 2021/09/19 - 00:41:51 | 200 |     6.41675ms |       127.0.0.1 | GET      "/posts/4"

Routes

Default UGin routes are listed below.

METHOD ROUTE FUNCTION
GET /posts/ github.com/yakuter/ugin/controller.(*Controller).GetPosts
GET /posts/:id github.com/yakuter/ugin/controller.(*Controller).GetPost
POST /posts/ github.com/yakuter/ugin/controller.(*Controller).CreatePost
PUT /posts/:id github.com/yakuter/ugin/controller.(*Controller).UpdatePost
DELETE /posts/:id github.com/yakuter/ugin/controller.(*Controller).DeletePost
GET /postsjwt/ github.com/yakuter/ugin/controller.(*Controller).GetPosts
GET /postsjwt/:id github.com/yakuter/ugin/controller.(*Controller).GetPost
POST /postsjwt/ github.com/yakuter/ugin/controller.(*Controller).CreatePost
PUT /postsjwt/:id github.com/yakuter/ugin/controller.(*Controller).UpdatePost
DELETE /postsjwt/:id github.com/yakuter/ugin/controller.(*Controller).DeletePost
POST /auth/signup github.com/yakuter/ugin/controller.(*Controller).Signup
POST /auth/signin github.com/yakuter/ugin/controller.(*Controller).Signin
POST /auth/refresh github.com/yakuter/ugin/controller.(*Controller).RefreshToken
POST /auth/check github.com/yakuter/ugin/controller.(*Controller).CheckToken
GET /admin/dashboard github.com/yakuter/ugin/controller.Dashboard

Gin Running Mode

Gin framework listens GIN_MODE environment variable to set running mode. This mode enables/disables access log. Just run one of these commands before running UGin:

// Debug mod
export GIN_MODE=debug
// Test mod
export GIN_MODE=test
// Release mod
export GIN_MODE=release

Packages

UGin uses great open source projects list below: Gin for main framework, Gorm for database and Viper for configuration.

go get -u github.com/gin-gonic/gin
go get -u github.com/jinzhu/gorm
go get -u github.com/jinzhu/gorm/dialects/postgres
go get -u github.com/jinzhu/gorm/dialects/sqlite
go get -u github.com/jinzhu/gorm/dialects/mysql
go get -u github.com/spf13/viper

Middlewares

1. Logger and Recovery Middlewares

Gin has 2 important built-in middlewares: Logger and Recovery. UGin calls these two in default.

router := gin.Default()

This is same with the following lines.

router := gin.New()
router.Use(gin.Logger())
router.Use(gin.Recovery())

2. CORS Middleware

CORS is important for API's and UGin has it's own CORS middleware in include/middleware.go. CORS middleware is called with the code below.

router.Use(include.CORS())

There is also a good repo for this: https://github.com/gin-contrib/cors

3. BasicAuth Middleware

Almost every API needs a protected area. Gin has BasicAuth middleware for protecting routes. Basic Auth is an authorization type that requires a verified username and password to access a data resource. In UGin, you can find an example for a basic auth. To access these protected routes, you need to add Basic Authorization credentials in your requests. If you try to reach these endpoints from browser, you should see a window prompting you for username and password.

authorized := router.Group("/admin", gin.BasicAuth(gin.Accounts{
    "username": "password",
}))

// /admin/dashboard endpoint is now protected
authorized.GET("/dashboard", controller.Dashboard)

What is next?

  • Ugin needs a user service and an authentication method with JWT.

More Repositories

1

gossl

Cross platform, easy to use SSL/TLS toolset
Go
186
star
2

go-concurrency

This repos has lots of Go concurrency, goroutine and channel usage and best practice examples
Go
142
star
3

go-interfaces

This repos has lots of Go interface usage and best practice examples
Go
116
star
4

go-developer-list

Turkish Go Developers
115
star
5

go-clean-code

Go
51
star
6

go-test-examples

Go Unit Test examples
Go
51
star
7

go-datatable

jQuery Datatable's serverside usage example with Golang
Go
38
star
8

go-channels-use-cases

Examples of golang channels use cases
Go
35
star
9

gol

Go implementation of Linux commands
Go
19
star
10

redis-vs-nats

This repo is prepared to test the performance of nats and redis in pubsub messaging
Go
19
star
11

rest-api-checklist

Go
17
star
12

gofind

Find all files and directories with pattern
Go
16
star
13

passwall-debian

The debian packager of PassWall.
Shell
16
star
14

agentgo

Hi! Agentgo is a tool for making remote command executions from server to client with golang, protocol buffers (protobuf) and grpc.
Go
16
star
15

optinator

Idiomatic way to fill structs with options logic
Go
13
star
16

golang-file-actions

Simple examples to show golang file actions
Go
9
star
17

go-buyuk-json-okuma

An example to show how to read large JSON files with JSON Data Streaming
Go
9
star
18

chanman

Chanman helps you to create queue channels and manage them gracefully.
Go
9
star
19

kudruk

Kudruk helps you to create queue channels and manage them gracefully.
Go
8
star
20

cert-generator

Self Signed SSL/TLS certificate generator script using openssl
Shell
7
star
21

go-dpi-packet

Go
7
star
22

go-grpc-protobuf

A simple example with documentation about using protocol buffers (protobuf) and grpc in golang
Go
6
star
23

panicer

panicer helps you to catch deferred panic handlers in goroutines
Go
6
star
24

yPhoneBook

Example PHP project using modern technologies Bootstrap, jQuery, AJAX and ezSQL
PHP
6
star
25

fogus

Focus app by blocking time wasting websites (work in progress)
Go
5
star
26

laravel-ajax-contact-form

An easy contact form example built with laravel and ajax (jquery)
PHP
5
star
27

flagopt

Command line based layout to parse arguments as options.
Go
5
star
28

jquery-slugify

jQuery Slugify with Turkish support
CSS
4
star
29

geekday

Go
4
star
30

sitemap-checker

4
star
31

golang-database-actions

A simple mini project to show usage of database with golang
Go
3
star
32

go-standard-library

A showcase for Go Standard Library
Go
3
star
33

go-network-programming

Go
3
star
34

builtinlogger

Go
2
star
35

tcell-firewall

This is an easy firewall draft
Go
2
star
36

react-native-test-project

JavaScript
2
star
37

kawaii

Go key value database as a bbolt wrapper
Go
2
star
38

httpgo

2
star
39

izmir-superpeer-json2go

Go
2
star
40

laravel-guestbook

An easy guestbook example to show usage of database actions in laravel with resource controller
PHP
2
star
41

go-concurrency-patterns

Golang concurrency pattern examples
2
star
42

matematik

Dört işlem paketi
Go
1
star
43

notebook

My personal notes about programming
1
star
44

woo-measurement-calculation

PHP
1
star
45

yakuter

1
star
46

centralog

Central logging server
HTML
1
star
47

yauthor-plugin

A wordpress plugin with WPBakery support to show posts of a category with author images
JavaScript
1
star
48

nsattrparser

The nsattrparser package provides a solution for extracting text from binary-encoded NSAttributedString data using golang.
Go
1
star
49

yGiris

PHP ile kendi yazmış olduğunuz yönetim panellerine güvenli bir şekilde girmek için kullanabileceğiniz AJAX (jQuery) ile güçlendirilmiş güzel görünümlü üye giriş formu
PHP
1
star
50

golang-for-loops

Simple examples to show usage of "for loops" in golang
Go
1
star