Categorygithub.com/jeamon/demo-redis
modulepackage
0.0.0-20240916222746-cf6aba917fc6
Repository: https://github.com/jeamon/demo-redis.git
Documentation: pkg.go.dev

# README

demo-redis

Build Status Go Report Card codecov GitHub go.mod Go version MIT License

This is a small go-based project to craft an API Backend which persist to Redis. It can be run on bare-metal computer as well in containerized environment with Docker and Docker-Compose. Keep watching for more features updates like redis-based pubsub async event for persisting data to file-like storage such as BoltDB and authenticate & authorize with JWT (Json Web Token) and log monitoring with Loki/Grafana and metrics monitoring with Prometheus/Grafana and tracing with OpenTelemetry/Tempo. The project mimic a DDD approach but in order to keep it minimal (avoid folders/packages) - I crafted it with some flat contextual files. Based on each file name, you can easily restructure to packages-based style.

Get-Started

You can run this project directly on your host machine (windows or linux or macos) or inside containerized environment (with docker-compose). I will be adding K8s manifest files soon. You can use the Make Tool for common tasks (check the Makefile for available actions). Make sure, you have git or git bash and make tools installed along with docker or docker desktop and docker-compose. All these tools could be installed even on windows-based machine. i.e install make tool on windows. You can use a hybrid approach like running some services (especially Redis container) inside a linux-based virtual machine and the golang app on your local machine. Feel free to use whatever approach that better suit to your setup. Finally you can always download golang from official page.

[Step 1] - Clone or download the repository on your local machine

$ git clone https://github.com/jeamon/demo-redis.git
$ cd demo-redis

[Step 2] - Open and check the config.yml and config.env files

Update the content (especially the redis and app host & port values) based on your setup or leave it like it is.

[Step 3] - Build and/or run the project

  • Method 1: Use docker-compose to build and spin up the project
$ make docker.build
$ make docker.run
  • Method 2: Run the Redis in docker and the App locally

Go inside the config.yml file and change the server host value to host: "127.0.0.1" Then change the redis host value to the exact IP address of the host where it is running. Finally do the same changes inside the config.env file for both server host and redis host.

  • create volume and start redis instance from your docker host

    $ docker volume create db.demo.redis.data
    $ docker run -d --name db.demo.redis -v db.demo.redis.data:/data -p 6379:6379 redis redis-server --requirepass "<secret>"
    
  • start the server on your local machine (depending if you have make or/and git tools)

    $ make local.run
    
    $ DRAP_REDIS_HOST=<IP.ADDRESS.REDIS.HOST> make local.run
    
    $ go run -ldflags "-X 'main.GitCommit=$(shell git rev-parse --short HEAD)' -X 'main.GitTag=$(shell git describe --tags --abbrev=0)' -X 'main.BuildTime=$(shell date -u '+%Y-%m-%d %I:%M:%S %p GMT')'" .
    
    $ go run .
    
  • delete the container and volume created before for redis on your docker host

    $ docker rm -f db.demo.redis
    $ docker volume rm db.demo.redis.data
    
  • connect to redis server from another temporary redis-cli container (on your docker host)

    $ docker run --rm -it --link db.demo.redis:redis-cli --name redis-cli redis sh
    $ redis-cli -h db.demo.redis
    $ auth default <secret>
    

Step 4: Check by performing basics requests (from curl or postman or browser)

## example of basic app checking
$ http://<server-address>:8080/

## example of fetching app status info
$ http://<server-address>:8080/status

## example of all books listing request
$ http://<server-address>:8080/v1/books

## example of pulling in-use app settings
$ http://<server-address>:8080/internal/configs
## example of book creation request

$ curl -X POST http://<server-address>:8080/v1/books \
   -H 'Content-Type: application/json; charset=UTF-8' \
   -d '{"title": "golang programming", "description": "Pratical golang exercices", "author": "Jerome Amon", "price": "10$"}'

Contact

Feel free to reach out to me before any action. Feel free to connect on Twitter or linkedin

# Packages

No description provided by the author

# Functions

CORSMiddleware intercepts each incoming HTTP calls then apply cors headers on it.
CreateLogFilePath returns the absolute path of the initial log file.
DecodeCreateOrUpdateBookRequestBody is a helper function to read the content of a book creation or update request.
No description provided by the author
GetBoltClient setup the database and the bucket then provides a ready to use client.
GetConnFromContext returns the connection saved into the context.
GetMemStats returns memory statistics with number of goroutines in json.
GetRequestNumberFromContext returns the request number set in the context.
GetRequestSourceIP helps find the source IP of the caller.
GetValueFromContext returns the value of a given key in the context if this key is not available, it returns an empty string.
InitConfig setup defaults values for non provided parameters and configures build tags values to be used if provided.
IsAppRunningInDocker checks the existence of the .dockerenv file at the root directory and returns a boolean result.
LoadAndInitConfigs loads in order the configs from various predefined sources then build the App configuration data.
LoadConfigEnv reads the environments variables and provides an instance of the App config.
LoadConfigFile provides an instance of config structure for the all application.
No description provided by the author
NewAPIHandler provides a new instance of APIHandler.
NewApp provides an instance of App.
NewBoltBookStorage provides an instance of bolt-based book storage.
No description provided by the author
No description provided by the author
NewClock returns a ready to use Clock with timezone sets to UTC in production environment and Local in dev env.
NewCustomResponseWriter provides CustomResponseWriter with 200 as status code.
NewIDsHandler returns a ready to use IDsHandler.
NewMockClocker returns a mocked instance with fixed time.
NewMockUIDHandler returns a mocked instance with predictable id.
NewRedisBookStorage provides an instance of redis-based book storage.
NewRedisClient provides a ready to use redis client.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
SaveConnInContext is the hook used by the server under ConnContext.
SetupLogging is a helper function that initializes the logging module.
ValidateCreateBookRequestBody is a helper function to check if the content of a book creation request is valid.
ValidateUpdateBookRequestBody is a helper function to check if the content of a book update request is valid.
WriteErrorResponse is used to send error response to client.
WriteResponse is used to send success api response to client.

# Constants

No description provided by the author
No description provided by the author
Predefinied Queue IDs.
Predefinied Queue IDs.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Predefinied Queue IDs.

# Variables

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

APIError is the data model sent when an error occurred during request processing.
APIHandler defines the API handler.
APIResponse is the data model sent when a request succeed.
No description provided by the author
No description provided by the author
Book represents a book entity.
No description provided by the author
Clock implements the Clocker interface.
Config defines the structure of the configuration file.
CustomResponseWriter is a wrapper for http.ResponseWriter.
IDsHandler implements the UIDHandler interface.
Maintenance holds app maintenance mode infos.
MiddlewareMap contains middlwares chain to use for public-facing and ops requests.
No description provided by the author
MockClocker implements a fake Clocker.
No description provided by the author
No description provided by the author
MockUIDHandler implements a fake UIDHandler.
No description provided by the author
RSyncWrite is a rotable and concurent safe file-based logs writer.
No description provided by the author
Statistics holds app stats for ops.
StatusResponse is the data model sent when status endpoint is called.
SyncWrite implements zap.SyncWriter.
No description provided by the author

# Interfaces

No description provided by the author
@externalDocs.description OpenAPI @externalDocs.url https://swagger.io/resources/open-api/.
BookStorage defines possible operations on book entity.
Clocker is an interface for getting current real time.
No description provided by the author
Queuer describes a queue.
TickerClocker is an interface which can provides the current time and a ticker.
UIDGenerator is an interface for getting a uid.

# Type aliases

No description provided by the author
MiddlewareFunc is a custom type for ease of use.
Middlewares is a custom type to represent a stack of middleware functions used to build a single chain.