Skip to content

The fastest way to deploy a restful api's with Gin Framework with a structured project that defaults to PostgreSQL database and JWT authentication middleware stored in Redis

License

Notifications You must be signed in to change notification settings

Massad/gin-boilerplate

Repository files navigation

alt tag

LicenseGitHub release (latest by date)Go VersionDB VersionDB Version

Build StatusGo Report Card

Join the chat at https://gitter.im/Massad/gin-boilerplate

Welcome toGolang Gin boilerplatev2

The fastest way to deploy a restful api's withGin Frameworkwith a structured project that defaults toPostgreSQLdatabase andJWTauthentication middleware stored inRedis

Configured with

  • go-gorp:Go Relational Persistence
  • jwt-go:JSON Web Tokens (JWT) as middleware
  • go-redis:Redis support for Go
  • Go Modules
  • Built-inCustom Validators
  • Built-inCORS Middleware
  • Built-inRequestID Middleware
  • FeaturePostgreSQL 12with JSON/JSONB queries & trigger functions
  • SSL Support
  • Environment support
  • Unit test
  • And few other important utilties to kickstart any project

Installation

$ go get github /Massad/gin-boilerplate
$ cd $GOPATH/src/github /Massad/gin-boilerplate
$ go mod init
$ go install

You will find thedatabase.sqlindb/database.sql

And you can import the postgres database using this command:

$ psql -U postgres -h localhost <./db/database.sql

Tip:

You will find that we added 2 trigger functions to the dabatase:

  • public.created_at_column()
  • public.update_at_column()

Those are added to theupdated_atandcreated_atcolumns to update the latest timestamp automatically in bothuserandarticletables. You can explore the tables and public schema for more info.

Running Your Application

Rename.env_rename_me to.env and place your credentials

$ mv.env_rename_me.env

Generate SSL certificates (Optional)

If you don't SSL now, changeSSL=TRUEtoSSL=FALSEin the.envfile

$ mkdir cert/
$ sh generate-certificate.sh

Make sure to change the values in.env for your databases

$ go run *.go

Building Your Application

$ go build -v
$./gin-boilerplate

Testing Your Application

$ go test -v./tests/*

Import Postman Collection (API's)

DownloadPostman-> Import -> Import From Link

https:// postman /collections/7f941b400a88ddd9c137

Includes the following:

  • User
    • Login
    • Register
    • Logout
  • Article
    • Create
    • Update
    • Get Article
    • Get Articles
    • Delete
  • Auth
    • Refresh Token

In Login request in Tests tab:

pm.test( "Status code is 200", function () {
pm.response.to.have.status(200);

var jsonData = JSON.parse(responseBody);
pm.globals.set( "token", jsonData.token.access_token);
pm.globals.set( "refresh_token", jsonData.token.refresh_token);

});

It captures theaccess_tokenfrom the success login in theglobal variablefor later use in other requests.

Also, you will find in each request that needs to be authenticated you will have the following:

Authorization -> Bearer Token with value of {{token}}

It's very useful when you want to test the APIs in Postman without copying and pasting the tokens.

On You

You will need to implement therefresh_tokenmechanism in your application (Frontend).

We have the/v1/token/refreshAPI here to use it.

For example:

If the API sends401Status Unauthorized, then you can send therefresh_tokenthat you stored it before from the Login API in POST/v1/token/refreshto receive the newaccess_token&refresh_tokenand store them again. Now, if you receive an error in refreshing the token, that means the user will have to Login again as something went wrong.

That's just an example, of course you can implement your own way.

Version 1

No longer supported

You will find the last update on v1 inv1-session-cookies-authbranch orv1.0.5 releasethat supported the authentication using thesessionandcookiesstored inRedisif needed.

  • RedisStore:Gin middleware for session management with multi-backend support (currently cookie, Redis).

Contribution

You are welcome to contribute to keep it up to date and always improving!

If you have any question or need help, drop a message athttps://gitter.im/Massad/gin-boilerplate

Credit

The implemented JWT inspired from this article:Using JWT for Authentication in a Golang Applicationworth reading it, thanksVictor Steven


License

(The MIT License)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.