- Sample
url-shortner
backend api to demonstrate golang backend using golang (gin) with unit test cases.
- golang (
go1.20
or above) - redis (
6.0
) - make (optional)
- Docker and docker-compose (optional)
Clone repo
git clone https://github.com/snghnaveen/url-shortener.git
Using docker-compose (recommended)
- Run docker-compose file
docker-compose up --build
Using go command
-
Make sure redis is running OR set
ENVIRONMENT
variable totesting
to skip redis server (It will use external package to mimic redis calls) -
Verify and if required update the configs in application.env
-
Run app
- Run make file
make run
OR
- Install packages
go mod tidy
- Run app
go run main.go
- Run tests
or
ENVIRONMENT=testing go test ./...
make test
You can github workflow the test case results.
├── Dockerfile.dev <--- Docker file for dev, uses air to run go app
├── Makefile
├── README.md
├── application.env <--- app config
├── db <--- Redis connection
│ ├──
│ ├──
├── docker-compose.yaml
├── go.mod
├── go.sum
├── main.go <--- main file
├── pkg
│ ├── resolver <--- service level logic
│ │ ├──
│ │ └──
│ ├── rest <--- REST api related common code
│ │ ├──
│ │ └──
├── routers
│ ├── api
│ │ └── v1 <--- API group
│ ├── routes.go <--- Registered endpoints
└── util <--- common code (logger, config etc)
├──
├──
Following are the APIs and their example response.
- Shorten given URL
Response :
curl --location 'http://localhost:8080/v1/api/shorten' \ --header 'Content-Type: application/json' \ --data '{ "url": "https://snghnaveen.github.io" }'
{ "error": false, "data": { "shorten_key": "qNGbdjC7", "shorten_url": "localhost:8080/resolve/qNGbdjC7" } }
- Get URL from shorten key
Response :
curl --location 'http://localhost:8080/v1/api/resolve/qNGbdjC7?type=json'
Note : Remove query param{ "error": false, "data": { "url": "https://snghnaveen.github.io" } }
type
to see actual redirection.
- Get metrics
Response :
curl --location 'http://localhost:8080/v1/api/metrics-top-requested'
{ "error": false, "data": [ { "domain": "snghnaveen.1.io", "rank": 1, "score": 101 }, { "domain": "snghnaveen.2.io", "rank": 2, "score": 51 }, { "domain": "snghnaveen.3.io", "rank": 3, "score": 34 } ] }