Skip to content

Web service CRUD using Golang with GIN for create REST api, MySQL as database, Viper as environment variable, JWT for secure service, redis to store token and Swaggo for API Documentation.

Notifications You must be signed in to change notification settings

Fikri1234/JWT_REST_Gin_MySQL

Repository files navigation

JWT_REST_Gin_MySQL

Web service CRUD using Golang with GIN for create REST api, MySQL as database, Viper as environment variable, JWT for secure service, redis to store token and Swaggo for API Documentation.

Prerequisites

  1. Go
  2. Gin
  3. Mysql
  4. Viper
  5. SQLMock
  6. Assert
  7. BCrypt
  8. JWT
  9. UUID
  10. Redis
  11. Swaggo

Getting Started

  1. Firstly, we need to get Gin, MySQL, Viper, sqlmock, assert, jwt, ksuid for UUID, and redis library dependencies for install it
go get github.com/gin-gonic/gin
go get github.com/go-sql-driver/mysql
go get github.com/spf13/viper
go get github.com/DATA-DOG/go-sqlmock
go get github.com/stretchr/testify/assert
go get golang.org/x/crypto/bcrypt
go get github.com/dgrijalva/jwt-go
go get github.com/segmentio/ksuid
go get github.com/gomodule/redigo/redis
  1. Download Redis for Windows

  2. After you download Redis, you’ll need to extract the executables and then double-click on the redis-server executable.

  3. Import dump.sql to your MySQL and configure your credential in folder resource Alt text

  4. Open cmd and type setx APP_ENVIRONMENT STAGING for default environment

  5. Open cmd in your project directory and type go test -v , you should get a response similar to the following: Alt text

  6. To run application,open cmd in your project directory and type

go run main.go

Sample Payload

  1. Login
  2. Logout
  3. Get User By Id
  4. Get User Detail By Id
  5. Get All User
  6. Get All User Detail
  7. Create User
  8. Create User Detail
  9. Update User
  10. Update User Detail
  11. Delete User By Id
  12. Delete User Detail By Id
  13. Example error response,in case Update User Detail

Implement Swaggo Documentation

  1. Open project directory which contains the main.go. Generate the swagger docs with the swag init command that wrap in the bash .\swaggo.sh

Alt text

  1. Import swaggo dependencies:
go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
  1. After installation, add General API annotation in main.go code, for example
// @securityDefinitions.apikey bearerAuth
// @in header
// @name Authorization
func main() {
	var err error

	// Setup database
	configuration.DB, err = configuration.SetupDB()
	if err != nil {
		log.Fatal(err)
	}
	defer configuration.DB.Close()

	port := viper.GetString("PORT")

	docs.SwaggerInfo.Title = "Swagger Service API"
	docs.SwaggerInfo.Description = "This is service API documentation."
	docs.SwaggerInfo.Version = "1.0"
	docs.SwaggerInfo.Host = "localhost:" + port
	docs.SwaggerInfo.BasePath = "/api"
	docs.SwaggerInfo.Schemes = []string{"http", "https"}

	// Setup router
	router := router.NewRoutes()
	url := swgGin.URL("http://localhost:" + port + "/swagger/doc.json")
	router.GET("/swagger/*any", swgGin.WrapHandler(swgFiles.Handler, url))

	log.Fatal(router.Run(":" + port))
}
  1. Add API Operation annotations in controller/service code
// getUserByID godoc
// @Summary show master user by id
// @Description get string by ID
// @Tags User
// @Accept  json
// @Produce  json
// @Param id path int true "User ID"
// @Success 200 {object} model.MUser
// @Failure 400 {string} string
// @Failure 404 {object} model.MUser
// @Failure 500 {string} string
// @Security bearerAuth
// @Router /user/{id} [get]
func getUserByID(c *gin.Context) {
	var user model.MUser
	paramID := c.Param("id")
	varID, err := strconv.ParseInt(paramID, 10, 64)

	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
		return
	}

	user, err = repository.GetUserByID(varID)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
		return
	}

	if (model.MUser{}) == user {
		c.JSON(http.StatusNotFound, user)
	} else {
		c.JSON(http.StatusOK, user)
	}
}
  1. Generate swaggo documentation Alt text

  2. Browse Swagger UI http://localhost:8999/swagger/index.html Alt text

  3. Execute login authentication endpoint Alt text

  4. If put wrong username or / and password,the API endpoit will give output something similiar to the following: Alt text

  5. Enter right username and password,then the API endpoit will give output something similiar to the following: Alt text

  6. Copy access_token from login response,and place it to Authorize with add a word Bearer. This wil be store the token for the rest API. Alt text

  7. Sample Endpoint Get User By Id

  8. Sample Endpoint Get All User

NOTES

For those having this problem when run swag init: Alt text

Check $GOPATH/bin where swag executable is present. Alt text

About

Web service CRUD using Golang with GIN for create REST api, MySQL as database, Viper as environment variable, JWT for secure service, redis to store token and Swaggo for API Documentation.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published