This Go package implements a simple HTTP URL shortener/redirector service. My goal with this package was to learn how to create HTTP server in Go that listens for requests on specific paths and redirects them to corresponding target URLs.
A key feature I wanted to implement was to add an ability to load URL mappings from multiple sources and chain the handlers together using a fallback mechanism.
The service works by chaining several http.Handler implementations together. When a request comes in:
- Database Check (
DBHandler): It first queries the SQLite database (urls.db) to see if the requested path exists in theurlstable. - JSON Check (
JSONHandler): If the path wasn't found in the DB, applications checks if the path exists in the mappings parsed from the provided JSON data. - YAML Check (
YAMLHandler): If the path wasn't found in JSON, applications checks the mappings parsed from the provided YAML data. - Map Check (
MapHandler): If the path wasn't found in YAML, applications checks the hardcoded Go map. - Base Mux: Finally, if the path hasn't been matched by any of the redirect handlers, the base
http.ServeMuxhandles the request.
- /sqlite redirects to https://www.sqlite.org/index.html
- /go-sqlite redirects to https://github.com/mattn/go-sqlite3
- /github redirects to https://github.com
- /google redirects to https://google.com
- /yahoo redirects to https://www.yahoo.com
- /duck redirects to https://duckduckgo.com
- /godoc redirects to https://godoc.org/
- /yaml-godoc redirects to https://godoc.org/gopkg.in/yaml.v2
- / responds directly with the text
Hello, world!
Any path not listed above responds directly with the text Hello, world!