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
- 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
-
Download Redis for Windows
-
After you download Redis, you’ll need to extract the executables and then double-click on the redis-server executable.
-
Import dump.sql to your MySQL and configure your credential in folder resource
-
Open cmd and type
setx APP_ENVIRONMENT STAGING
for default environment -
Open cmd in your project directory and type
go test -v
, you should get a response similar to the following: -
To run application,open cmd in your project directory and type
go run main.go
- Login
- Logout
- Get User By Id
- Get User Detail By Id
- Get All User
- Get All User Detail
- Create User
- Create User Detail
- Update User
- Update User Detail
- Delete User By Id
- Delete User Detail By Id
- Example error response,in case Update User Detail
- Open project directory which contains the
main.go
. Generate the swagger docs with theswag init
command that wrap in the bash.\swaggo.sh
- 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
- 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))
}
- 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)
}
}
-
Browse Swagger UI http://localhost:8999/swagger/index.html
-
If put wrong username or / and password,the API endpoit will give output something similiar to the following:
-
Enter right username and password,then the API endpoit will give output something similiar to the following:
-
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.