Go REST API (Part 2)
Adding endpoints to a REST server
In this post we are going to expand on our REST API server enabling methods for our endpoints, and add the ability to Create and Delete users.
Methods for Endpoints
Now that we have a way to retrieve our user, we should restrict it to just the GET method. To do this we’ll use the mux.Router.Methods
function. This takes a list of methods we want this endpoint to respond to. We’ll also go ahead and add our method for creating a new user also.
|
|
Creating users
As you can see we don’t need to provide an ID for creating a user, as the system should provide the next available ID to us, using our new function maxID
. We’ll need to create our app.CreateUser
function. Creating a user will be slightly more complicated than retrieving a user, mostly because we will need to get data from the client’s body. To do this, we’ll create a bytes.Buffer
to read the req.body
into, then use json.Unmarshal
to convert it from a JSON string to a user
object.
|
|
We see here that we are using the w.Header().Set()
method to set a Location header which will tell the client the location of the newly created user. We also return the JSON formatted version of our new user.
Now to test this method, we can’t just simply request the page from our browser, because your browser sends a GET request. We’ll need to send the request using something more specialized. For this test, we’ll use curl:
|
|
This will create a second user in our database (or multiple if run more than once), and we can verify our new user is created by running curl on the location returned above:
|
|
Deleting Users
Deleting users is a fairly easy process. We’ll add a new endpoint for user/{id}
for the DELETE method. Once we have the ID, we’ll verify the ID exists in the database, and delete the key for that user from our map and return a 200. If the key does not exist, we’ll return a 404.
|
|
Great! Let’s test it out with curl again:
|
|
Conclusion
We’ve expanded on our server adding the ability add and remove users. Next we’ll add the ability to Update by replacing using PUT and modify using PATCH.
Here is a gist of our main.go from this post.