...

/

Setting up the Structure of Application

Setting up the Structure of Application

This lesson provides detailed code for designing the application and its explanation.

When our application is running in production, it will receive many requests with short URLs, and several requests to turn a long URL into a short one. But, which data structure will our program stock this data in?

Both URL-types (A) and (B) from the last lesson are strings. Moreover, they relate to each other: given (B) as a key, we need to fetch (A) as its value, i.e., they map to each other. To store our data in memory, we need such a map structure, a map[string]string. The key type is written between [ ], and the value type follows, as we learned all about maps in Chapter 6. In any non-trivial program, it is useful to give the special types that you use a name. In Go, we do this with the keyword type, so we define a: type URLStore map[string]string. It maps short URLs to long URLs; both are strings.

To make a variable of that type named urls, just use: urls := make(URLStore). Suppose we want to store the mapping of http://goto/a to http://google.com/ in urls; we can do this with the statement:

urls ["a"] = "http://google.com/"

We just store the suffix of http://goto/ as a key, and what comes before the key is a fixed URL prefix.

To retrieve its corresponding long URL given “a”, we write:

url := urls ["a"]

Then, the value of url is equal to “http://google.com/”. Note that with := we don’t need to say that url is of type string; the compiler deduces the type from the value on the right side.

Making it thread-safe

Our URLStore variable is the central memory data store here. Once we get some traffic, there will be many ...