Simple Golang User Login & Register using MySQL Database & JWT
=============================================================
List Route for API
POST => 0.0.0.0:9000/register
To register user
Request :
$.ajax({ url:'http://:9000/register', type:'POST', data:'{ "Username":"user", "Password":"pass", "Nama_lengkap":"Your Name", }', contentType: "application/json; charset=utf-8", success: function(data){ console.log(data) } })
Response :
{ "message" : "done", "nama" : "Your Name, "username" : "user", }
POST => 0.0.0.0:9000/login
Just send Http POST request with username & password as body data as JSON
for example (AJAX):
$.ajax({ url:'http://:9000/login', type:'POST', data:'{ "Username":"user", "Password":"pass" }', contentType: "application/json; charset=utf-8", success: function(data){ console.log(data) } })
Response :
{ "message" : "done", "nama" : "Your Name", "username" : "user", "token" : "", "refreshToken" : "", }
POST => 0.0.0.0:9000/relogin
This route is for make auto login by checking token in database. if the Authorization token is not valid anymore, then you can access this url to get new JWT Token without sending username & password by sending refresh_token that you got when you attempt login. the relogin controller will check the refresh_token in database. if it is still valid, then you can get new token & refresh_token.
for example (AJAX):
$.ajax({ url:'http://:9000/relogin', type:'POST', data:'{ "Username":"user", "Token":"refresh_token" }', contentType: "application/json; charset=utf-8", success: function(data){ console.log(data) } })
Response :
{ "message" : "done", "nama" : "Your Name", "username" : "user", "token" : "", "refreshToken" : "", }
// Restricted
GET => 0.0.0.0:9000/
To access restricted Route add Authorization to header
'Authorization': 'Bearer ' + token
for example (AJAX):
$.ajax({ url:'http://:9000/', type:'GET', headers: { 'Authorization': 'Bearer ' + token }, success: function(data){ console.log(data) } })
Response :
{ "data" : "user", }
POST => 0.0.0.0:9000/logincheck
To manualy check JWT token validity
'Authorization': 'Bearer ' + token
for example (AJAX):
$.ajax({ url:'http://:9000/logincheck', type:'GET', headers: { 'Authorization': 'Bearer ' + token }, success: function(data){ console.log(data) } })
Response :
{ "data" : "user", }
=============================================================
To deploy
- Git Clone https://github.com/cakrizky7/GoLangLoginBackEnd.git
- go get
- Prepare the Database
3a. Add table "users"
3b. Add fields:Id varchar(128) -> Primary Key Username varchar(64) -> Unique Password varchar(128) Nama_lengkap varchar(64) Token_expired text Created_at timestamp Updated_at timestamp
- Set database connection config in "config/app.conf"
- go run main.go