Search⌘ K
AI Features

Solution 4: Working with REST APIs

Explore how to develop RESTful servers in Go by structuring HTTP handlers into packages and testing client-server interactions using curl. Understand the organization of handler functions and how to reference them from the main application for smooth API development.

We'll cover the following...

Solution

Here are the handlers.go functions separated into individual files in the handlers directory.

Let’s test the RESTful server using curl(1). Here are the commands to run the client:

Shell
# Command to test the /time handler:
curl localhost:1234/time
# Command to test the default handler:
curl localhost:1234/
# Command to test the unsupported handler:
curl localhost:1234/doesNotExist
# Command to test the unsupported HTTP method with a supported endpoint:
curl -s -X PUT -H 'Content-Type: application/json' localhost:1234/getall
# Command to test the getall endpoint:
curl -s -X GET -H 'Content-Type: application/json' -d '{"username":
"admin", "password" : "newPass"}' localhost:1234/getall
# Command to test the logged endpoint:
curl -X GET -H 'Content-Type: application/json' -d '{"username":
"admin", "password" : "newPass"}' localhost:1234/logged
# Command to test the /username/{id} endpoint
curl -X GET -H 'Content-Type: application/json' -d '{"username":
"admin", "password" : "newPass"}' localhost:1234/username/7
# Command to test the /getid/{username} endpoint:
curl -X GET -H 'Content-Type: application/json' -d '{"username":
"admin", "password" : "newPass"}' localhost:1234/getid/admin
# Command to test the /add endpoint:
curl -X POST -H 'Content-Type: application/json' -d '[{"username":
"admin", "password" : "newPass", "admin":1}, {"username": "packt",
"password" : "admin", "admin":0} ]' localhost:1234/add
# Command to test the /login endpoint:
curl -X POST -H 'Content-Type: application/json' -d '{"username":
"admin", "password" : "newPass"}' localhost:1234/login
# Command to test the /logout endpoint:
curl -X POST -H 'Content-Type: application/json' -d '{"username":
"admin", "password" : "newPass"}' localhost:1234/logout
# Command to test the /update endpoint:
curl -X PUT -H 'Content-Type: application/json' -d '[{"username":
"admin", "password" : "newPass", "admin":1}, {"username": "admin",
"password" : "justChanged", "admin":1} ]' localhost:1234/update
# Command to test the /update endpoint:
curl -X PUT -H 'Content-Type: application/json' -d '[{"Username":
"packt","Password":"admin"}, {"username": "admin", "password" :
"justChanged", "admin":1} ]' localhost:1234/update
# For the DELETE HTTP method, we need to test the /username/{id} endpoint:
curl -X DELETE -H 'Content-Type: application/json' -d '{"username":
"admin", "password" : "justChanged"}' localhost:1234/username/6 -v

To execute the client side successfully, open a new terminal window and copy and paste ...