This is an example of how to create a URL shortener using:
The apis logic need storage, that is passed as an interface
to make easier change it
go mod
The code NOT autogenerated is included in the following packages/files:
storage
package (logic of storage)middlewares
package (logic to redirect, prometheus)url_implementation
package (logic of APIs)restapi/operation/configure_url_shortener.go
file (linking pieces)swagger-ui/swagger.yml
file (open-api definition, used to auto-generate the code)The code autogenerated is NOT covered by tests, everything else has a coverage of ~ 80%
To add new Api modify swagger-ui/swagger.yml
and run:
$swagger generate server -f ./swagger-ui/swagger.yml --exclude-main
Be aware, if you modify any autogenerated file it will be overwritten running such command.
Run test running:
$go test ./...
To execute the server clone the repo, cd into it and run:
$go run ./cmd/url-shortener-server/main.go --port 35307
Navigate to localhost:35307/swagger-ui
to visualise the UI and test APIs with a frontend
Navigate to localhost:35307/metrics
to check metrics, in particular url_redirected
keeps track of redirection since last execution
There are three methods under /api
:
/api/url
that accept in the json body the URL to make shorter/api/url/{shortURL}
that returns the URL corresponding to shortURL/api/url/{shortURL}
that delete the URLShortened URLs will be like short-abcdefghil
and can be used as follows localhost:35307/short-abcdefghil
If you try to navigate to a shortened url that does not exist (es: localhost:35307/short-notExisting
) you will be redirected to http://www.notfound.com