In this quickstart, you will learn how to build a REST API in Go that will store and retrieve user information backed by a HASH data structure in Azure Cache for Redis.
- Azure subscription - create one for free
- Go (preferably version 1.13 or above)
- Git
- An HTTP client such curl
Start by cloning the application from GitHub.
-
Open a command prompt and create a new folder named
git-samples
.md "C:\git-samples"
-
Open a git terminal window, such as git bash. Use the
cd
command to change into the new folder and install the sample app.cd "C:\git-samples"
-
Run the following command to clone the sample repository. This command creates a copy of the sample app on your computer.
git clone https://github.com/Azure-Samples/azure-redis-cache-go-quickstart.git
The application accepts connectivity and credentials in the form the environment variables.
- Fetch the Host name and Access Keys (available via Access Keys) for Azure Cache for Redis instance in the Azure portal
Set them to the respective environment variables
set REDIS_HOST=<Host name e.g. <name of cache>.redis.cache.windows.net>
set REDIS_PASSWORD=<Primary Access Key>
In the terminal window, change to the correct folder. For example:
cd "C:\git-samples\azure-redis-cache-go-quickstart"
- In the terminal, run the following command to start the application.
go run main.go
The HTTP server will start on port 8080
.
Create a few user entries. The below example uses curl client:
curl -i -X POST -d '{"id":"1","name":"foo1", "email":"[email protected]"}' localhost:8080/users/
curl -i -X POST -d '{"id":"2","name":"foo2", "email":"[email protected]"}' localhost:8080/users/
curl -i -X POST -d '{"id":"3","name":"foo3", "email":"[email protected]"}' localhost:8080/users/
Fetch an existing user with its id
:
curl -i localhost:8080/users/1
you should get JSON response as such
{
"email": "foo1@bar",
"id": "1",
"name": "foo1"
}
If you try to fetch a user that does not exist, you will get an HTTP 404
. For example:
curl -i localhost:8080/users/100
#response
HTTP/1.1 404 Not Found
Date: Fri, 08 Jan 2021 13:43:39 GMT
Content-Length: 0