Start learning free

LESSON 169 OF 173 · BACKEND: YOUR OWN API

Short Links: Create in Go

Practice

A new project starts here: a link shortener. It gives each long URL a short code and remembers the pair. Later, whoever opens the code is sent on to the long URL. You will build it over five lessons, starting now.

Codes in base 36: codes count like numbers, 1, 2, 3…, but with 36 characters instead of 10: after 9 come a, b, … z, and only then 10. As in base 10, % 36 gives the last digit and / 36 drops it (dividing two ints drops the remainder). For example, 100 = 2 × 36 + 28, and the character for 28 is s, so 100 is written "2s".

Creating with POST: a handler that stores something new is registered for POST, decodes the JSON body with json.NewDecoder(r.Body).Decode and answers 201 Created. For example, on another route:

app.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) {
    var data map[string]string
    json.NewDecoder(r.Body).Decode(&data)
    notes = append(notes, data["text"])
    writeJSON(w, 201, map[string]string{"text": data["text"]})
})

Your app must give these answers, in this order:

POST /links  {"url": "https://www.python.org/downloads/"}
  →  201  {"code": "1", "url": "https://www.python.org/downloads/"}
POST /links  {"url": "https://en.wikipedia.org/wiki/URL_shortening"}
  →  201  {"code": "2", "url": "https://en.wikipedia.org/wiki/URL_shortening"}
POST /links  {"url": "https://flask.palletsprojects.com/en/stable/quickstart/"}
  →  201  {"code": "3", "url": "https://flask.palletsprojects.com/en/stable/quickstart/"}
GET /check/codes  (the check calls your makeCode)
  →  1 → "1", 9 → "9", 10 → "a", 35 → "z", 36 → "10", 37 → "11", 1295 → "zz", 1296 → "100"

Your task: the starting code already has writeJSON, digits, the map links and counter. Write makeCode(number int) string, which turns a number into its base-36 code. Then, inside newApp, add the POST /links handler: it gives the URL the next code, stores the pair in links and answers 201 with the code and the URL.


Assignment
Follow the Coding Tutorial to write makeCode and the POST /links handler.


Hint
Build the code from the back: each new character goes in front of code, and string(…) turns the byte digits[…] into text. Add 1 to counter before you make the code, and pass 201 to writeJSON.


STEP 1 OF 12
    Ctrl + Enter to check

    Own Links Create in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free