• Stars
    star
    144
  • Rank 255,590 (Top 6 %)
  • Language
    Go
  • License
    MIT License
  • Created about 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang URL shortener and bookmarker service with UI, API, Cache, Hits Counter and forwarder using postgres and redis in backend, bulma in frontend. Think of it as self hosting ready url shortener.

urlsh

Latest Version Software License lint test Tweet Support

urlsh is URL shortener application built on Go language.

It does not use external libraries except the gorm for postgres database and minimal redis module redigo.

URLSH

Usage

Web client

Just visit urlssh.xyz. You can also integrate API for programmatic usage.

Terminal client

If you live inside the command line terminal, you can install a client:

go get github.com/adhocore/urlsh/cmd/urlshc

or, with newer go versions

go install github.com/adhocore/urlsh/cmd/urlshc

Make sure $GOPATH or $HOME/go/bin is in your $PATH or %path%, then use it like so:

# show help
urlshc -h

# shorten a url
urlshc -url 'https://your.long.url/here'

# shorten a url with keywords and expiry date
urlshc -url 'https://your.long.url/here' -keywords 'word-1,word2' -expires '2022-12-31'

# if you have self hosted or local instance of urlsh, pass in URLSH_HOST (with domain only)
URLSH_HOST=https://your.urlsh-instance.com urlshc -url 'https://your.long.url/here'

Read below for self hosting, API integration and/or contributing to urlsh.


Getting source

git clone [email protected]:adhocore/urlsh.git
cd urlsh

Configuring

It should be configured using env variables.

Please check .env.example for available variables and explanation.

DATABASE_URL is always required and is string of the following form:

DATABASE_URL=postgres://user:pass@host:port/dbname

When running urlsh with docker-compose, the preferred way, DATABASE_URL is automatically set from POSTGRES_* variables.

Please note that urlsh does not ship with .env loader so to run it in bare metal, one needs to use export KEY=VALUE or source .env manually.

If REDIS_URL is provided with redis://host:port, then it will cache popular urls, the popularity threshold is hard coded to minimal value in common.constant. The cache will sync when short url is deleted and sometimes when expired. The hit counters will however sync in realtime.

Setting up docker

To set up dockerized urlsh, run the commands below:

# first time only
cp .example.env .env

# change auth token for admin if you want in `.env` file
# APP_ADMIN_TOKEN=<something crypto secure random hash>

docker-compose up

After a few seconds, you should be able to browse to localhost:2000.

Testing

For running tests,

docker-compose exec urlsh sh -c "APP_ENV=test go test ./..."

# for coverage
docker-compose exec urlsh sh -c "APP_ENV=test go test -cover ./..."

APP_ENV=test is not required but ensures that tests are run against clone database with name prefixed by test_. Normally test db is already prepared if you use docker-compose.


API Endpoints

GET /status

Status route for health/status check.

Response payload

{
    "status": 200,
    "message": "it works"
}

POST /api/urls

Creates a new short code for given URL.

Request example

  • url: string, required, http/https/ftp only
  • expires_on: string, optional, utc date yyyy-mm-dd hh:mm:ss, default=9999-01-01
  • keywords: array of strings, 2-25 chars each, max 10 keywords
{
    "url": "http://somedomain.com/some/very/long/url",
    "expires_on": "",
    "keywords": ["key", "word"]
}

Response example

{
    "status": 200,
    "short_code": "qaFxz",
    "short_url": "http://localhost:2000/qaFxz"
}

If env var APP_ALLOW_DUPE_URL is set to 0 or empty, then trying to shorten same URL again will return status 409 and payload will contain existing short_code. However if existing short_code is deleted, it will be shortened as usual.


GET /{shortCode}

Redirects the shortcode to original long URL.

Response payload

In case short code exists it responds with 301 redirect.

If the short code is expired or deleted, it responds like so:

{
    "status": 410,
    "message": "requested resource is not available"
}

GET /api/admin/urls

Authentication

Token required in Authorization header like so:

Authorization: Bearer <token>

Request query

The query params are optional.

page=<int>
short_code=<str>
keyword=<str>

Examples:

  • /api/admin/urls?short_code=somecode
  • /api/admin/urls?page=1&keyword=something

Response example

Response contains multiple matching url object inside urls array.

{
    "status": 200,
    "urls": [
        {
            "short_code": "X5JkFd",
            "origin_url": "http://somedomain.com/some/very/long/url",
            "hits": 1,
            "is_deleted": false,
            "expires_on": "9999-01-01T00:00:00Z"
        }
    ]
}

DELETE /api/admin/urls

Authentication

Token required in Authorization header like so:

Authorization: Bearer <token>

Request query

Query param short_code is requied.

Example: /api/admin/urls?short_code=somecode

Response example

If delete success:

{
    "status": 200,
    "deleted": true
}

If the code does not exist:

{
    "status": 404,
    "message": "the given short code is not found"
}

Using postman

urlsh comes with postman collection and environment to aid manual testing of endpoints.

Open the postman app, click Import at top left, select Folder and drag/choose postman folder of this repo. You may need to adjust the token in postman urlsh env if you have configured APP_ADMIN_TOKEN.

The collection comes with post/pre request hooks for requests so you can just run the endpoints one after another in postman UI.

For redirect request, you have to disable postman follow redirects from Settings > General > Automatically follow redirects.

License

Please check license file.


Other projects

My other golang projects you might find interesting and useful:

  • gronx - Lightweight, fast and dependency-free Cron expression parser (due checker), task scheduler and/or daemon for Golang (tested on v1.13 and above) and standalone usage.
  • fast - Check your internet speed with ease and comfort right from the terminal.
  • goic - Go Open ID Connect, is OpenID connect client library for Golang, supports the Authorization Code Flow of OpenID Connect specification.
  • chin - A GO lang command line tool to show a spinner as user waits for some long running jobs to finish.

More Repositories

1

php-cli

PHP Console Application made easy- build great console apps with ease. Comes with Zero Dependency and Autocompletion support. Think of it as a PHP cli application framework.
PHP
333
star
2

gronx

Lightweight, fast and dependency-free Cron expression parser (due checker, next/prev due date finder), task runner, job scheduler and/or daemon for Golang (tested on v1.13+) and standalone usage. If you are bold, use it to replace crontab entirely.
Go
317
star
3

php-jwt

Ultra lightweight, dependency free and standalone JSON web token (JWT) library for PHP5.6 to PHP8.2. This library makes JWT a cheese. It is a minimal JWT integration for PHP.
PHP
271
star
4

docker-phpfpm

Lightweight (~100mb) Docker PHP FPM for both arm and amd arch on alpine 3.17 with PHP8.0.30/8.1.25/8.2.12 (also 7.4.33) with ~82-84 useful extensions (you can disable not necessary ones easily)
Dockerfile
96
star
5

phint

Interactively scaffolds and init new (or fixup old) PHP project/library with sane defaults using templates in no time
PHP
93
star
6

please

please is semver release made easy, detects current version from API or tags and next version from commits, creates detailed changelogs that are configurable.
Shell
86
star
7

fast

Check your internet speed/bandwidth right from your terminal. Built on Golang using chromedp
Go
81
star
8

php-cron-expr

Ultra lightweight, Dependency free and Super Fast Cron Expression parser for PHP
PHP
51
star
9

htmlup

Light and fast markdown parser, that parses markdown in a way human does
PHP
50
star
10

php-json-fixer

Fix truncated JSON data
PHP
45
star
11

php-underscore

PHP underscore inspired &/or cloned from _.js, with extra goodies like higher order messaging
PHP
44
star
12

phalcon-ext

Foundations, adapters, extensions, middlewares and utilities for Phalcon v4
PHP
42
star
13

tusc.sh

tus 1.0.0 client protocol implementation for bash. Resumable large file upload to Tus sever from terminal using bash script
Shell
32
star
14

chin

A Go lang library to show a spinner as user waits for any long running jobs to finish.
Go
31
star
15

goic

Golang OpenID Connect Client
Go
28
star
16

php-json-comment

Lightweight JSON comment and trailing comma stripper library for PHP with support for literal newlines and nested JSON strings.
PHP
27
star
17

php-env

A small and fast .env loader for PHP
PHP
23
star
18

with

With provides object like fluent interface for scalars and non-objects
PHP
17
star
19

jquery-plugins

jQuery plugins: BS calendar & datepicker, auto form filler, css grid float top, lazy & ajax pagination
JavaScript
16
star
20

crx-jtrans

jTransliter - the roman to unicode transliter as Google chrome extension
JavaScript
15
star
21

dsa

data structure and algorithm - examples and implementations
PHP
15
star
22

stiky

modular backbonejs application for sticky notes
JavaScript
14
star
23

jsonc

Golang (v1.13+) JSON5 preprocessor supporting comments, trailing comma, unquoted key/single-quoted string, hex number, trailing decimal point, literal newlines and more.
Go
14
star
24

twig-yall

Resource lazy loader extension for twig using malchata/yall.js
PHP
12
star
25

crx-loshin

loshin, the Load Shedding Indicator
JavaScript
12
star
26

php-cli-syntax

PHP Code Syntax Highlighter and/or exporter for CLI. Zero Dependency.
PHP
11
star
27

vue-inventory

Vue JS inventory app for hotel
HTML
11
star
28

php-env-bench

Benchmarking env loaders/parsers for PHP.
PHP
11
star
29

fsb

f...ing simple benchmark(ing)
PHP
10
star
30

get-in

Handy Traversal of chained objects with error trap and default value (suited for View)
PHP
9
star
31

sublime-phpcsfixer

A simple and minimal plugin for sublime editor to fix php files with php-cs-fixer via context menu
Python
9
star
32

php-cron-bench

Benchmarking cron parsers for PHP.
PHP
9
star
33

asserts

More PHPUnit assertions as a Trait
PHP
9
star
34

log-viewer

Simple log viewer app built with Lumen framework and VueJS
PHP
9
star
35

php-polyfills

Miscellaneous polyfills for older PHP versions
PHP
8
star
36

win-cli-launcher

a command line launcher for windows os
Batchfile
8
star
37

py-routes

Python recursive shortest path algo to find the optimal route between two points in terms of number of stops and duration
Python
8
star
38

php-tools

php tools for string, numbers, dates etc
PHP
7
star
39

gh-sc

Cancel all but the last SC automatically
JavaScript
7
star
40

plastic

PHP elasticsearch wrapper designed to be minimal, intuitive and dependency free
PHP
7
star
41

ci-captcha

Easy, hassle free, plug and play Code Igniter captcha library [OLD CODE]
PHP
7
star
42

live-console

PHP live console in browser
PHP
6
star
43

crx-adblock

chrome extension to hide/block custom ads
JavaScript
6
star
44

crx-joom

auto zoom the webpage for more readability and less eye stress
JavaScript
6
star
45

adhocore.github.io

adhocore.github.io
HTML
5
star
46

adhocore

5
star
47

php-adhocore

A PHP framework I created in early 2013 - inspired by CodeIgniter. Published here for historical reason. It was still a work in progress and was not complete- I am afraid it may as well never be. Check the initial commit.
PHP
5
star
48

leetcode

Just some leet code solutions in Python
Python
3
star
49

zshist

ZSH history manager: merge/deduplicate/normalize history entries for zsh, arrow suggestion UX is improved (plus save space, remove redundancy)
Go
2
star
50

opentelemetry

Temp mirror of old version of open-telemetry/opentelemetry
PHP
2
star
51

import-configuration-jms

Clone of techdivision/import-configuration-jms
PHP
2
star
52

docker-php-fpm-old-alpine

Mirror of official PHP docker images built on alpine 3.13/3/14 instead of 3.15/3.16
Dockerfile
2
star