# Packages
# README
gRPC Template 🚀
Template for gRPC backend project.
This project was documented with Obsidian, check out the docs for more
Getting Started 🏁
-
Clone project with
git clone [email protected]:Jerinji2016/grpc-template.git
-
To rename module, change the module in
go.mod
and replace all the imports respective in other files -
Run
git mod tidy
-
Create a
.env
file with envorinment variables with schema below -
Start serving with
go run src/cmd/server.go
.
Environment Schema 🍁
PORT=50051
JWT_SECRET=your_secret_key
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=admin
DB_PASSWORD=secret
DB_NAME=grpc_sample
LOG_OUTPUT_DIR=logs
LOG_FILE_FORMAT=LOG_2006-01-02 15:04:05.log
Multiple enviroments
For multiple enviroments create file with name
.env.production
or.env.development
, and make sure you pass the environment while runningsrc/cmd/server.go
.ENVIRONMENT=production go run src/cmd/server.go
Authentication 🔑
JWT is used authentication and is defined in src/pkg/auth/jwt.go
. To start add jwt dependency with:
go get github.com/golang-jwt/jwt/v4
To remove a rpc method from jwt check add the full method name that can be obtained from constant in generated code as follows in isPublicMethod
middleware.go
// ...
func (a *AuthInterceptor) isPublicMethod(fullMethod string) bool {
var publicMethods = []string{
pb.AuthenticationService_Login_FullMethodName,
pb.AuthenticationService_Register_FullMethodName,
// add other methods here
}
return slices.Contains(publicMethods, fullMethod)
}
Logger 🪵
Logger is implemented with logrus package. To start add logrus dependency with:
go get github.com/sirupsen/logrus
Logger is configured to add logs to a log file. This can be set to log to console by checking environment (say log to console for development environment)
Logger Configuration
Set up logger configuration in .env file as follow
LOG_OUTPUT_DIR: log files will be created in this directory. (Optional)
LOG_FILE_FORMAT: file name format. (Optional)
Use logger with:
// info log
logger.infoLog("FYI %v!", info)
// debug log
logger.DebugLog("Hello %v!", variable)
// error log
logger.ErrorLog("Error: %v", err)
// warning log
logger.WarnLog("Careful: %v", warning)
Database 🗄️
Database is implemented with postgresql with gorm.
Start by installing the gorm
& postgres
as this documentation:
go get -u gorm.io/gorm
go get -u gorm.io/driver/postgres
Define you schemas in src/internal/models/
and then add the schema instance to schema
defined on top in db.go
.
schemas := []interface{}{
&models.Post{},
// other models
}
Make sure postgres services are running and credentials mentioned in .env is setup.