REST API With Golang and Gorilla Mux

source phpflow.com

In this tutorial, you are going to be building a fully-fledged REST API that exposes GET, POST, DELETE and PUT endpoints that will subsequently allow you to perform the full range of CRUD operation.

In order to keep this simple and focus on the basic concepts, we won’t be interacting with any backend database technologies to store the posts that we’ll be playing with. However, we will be writing this REST API in such a way that it will be easy to update the functions we will be defining so that they make subsequent calls to a database to perform any necessary CRUD operations.

You will need Go version 1.11+ installed on your development machine.

REST Architectures

REST is everywhere these days, from websites to enterprise applications, the RESTful architecture style is a powerful way of providing communication between separate software components. Building REST APIs allow you to easily decouple both consumers and producers and are typically stateless by design.

JSON

For the purpose of this tutorial I’ll be using JavaScript Object Notation as a means of sending and receiving all information and thankfully Go comes with some excellent support for encoding and decoding these formats using the standard library package, encoding/json.

Marshaling

In order for us to easily We can easily convert data structures in GO into JSON by using something called marshaling which produces a byte slice containing a very long string with no extraneous white space.

Getting Started

we will create a very simple server which can handle HTTP requests. To do this we’ll create a new file called main.go. Within this main.go file we’ll have four functions to perform CRUD operations.

Post Structure

Our Struct contains the 5properties we need to represent all of the posts in the API. In order for this to work, we’ll also have to import the "encoding/json" package into our list of imports.

In the main function we will call a function setInitialDatathat will set up the mock data for our API so that we can retrieve and modify it later on.

Retrieving All Posts

In this part of the tutorial we are going to create a new REST endpoint which, when hit with a HTTP GET request will return all of the posts.

We’ll first start off by creating a new function called GetAllPosts, which will do the simple task of returning our pre-populated Posts variable, encoded in JSON format:

json.NewEncoder(w).Encode(posts) handles the job of encoding our posts array into a JSON string and then writing as part of our response.

we’ll also need to add a new route to our main function that will map any calls to http://localhost:3000/ to our newly defined function. We will be using mux Router for the routing. Like the standard http.ServeMux, mus.Routermatches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions.

Query Post

To query for a specific post we will be passing id in the query params and based on the id we will the post corresponding to that id .

The implementation of the handler QueryPost will contain the logic for getting the query param from the endpoint.

If we navigate to http://localhost:3000/post?id=1 after we’ve now run this, you should see data corresponding to theID: 1 being printed out within the browser.

Creating and Updating Posts

In this part, we will build the Create, Update and DELETE part of a CRUD REST API. We have already covered the R with the ability to read both single post and all posts

Creating new Post

we will create a new function which will do the job of creating this new post. Our handler for creating a post will look like this.

We will be using a random function from the math package to generate a unique id for our new post. We will be adding the body received in the HTTP request.

Deleting Post

In order to delete a post, we need to expose a DELETE endpoint within your API that will take in an identifier and delete whatever is associated with that identifier.

we will be creating another endpoint which receives HTTP DELETE requests and delete the post if they match the given Id path parameter. We will create the DeletePost function.

Updating Post Endpoint

The last endpoint we will need to implement is the Update endpoint. This endpoint will be a HTTP PUT based endpoint and will need to take in an Id path parameter, the same way we have done for our HTTP DELETE endpoint, as well as a JSON request body.

Path Variables

With the help of gorilla mux router, we can add variables to our paths and then pick and choose what posts we want to return based on these variables.

we’ve added {id} to our path. This will represent our id variable that we’ll be able to use when we wish to return only the post that features that exact key.

Now that we’ve done that, in our UpdatePost function, we can obtain this {id} value from our URL and we can return the post that matches these criteria.

The full source code can be found here.

You can also follow me Aditya Joshi or LinkedIn. You can find me on GitHub? If that’s too social for you, just drop a mail to adityaprakashjoshi1@gmail.com if you wish to talk tech with me.

Have a nice day!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aditya Joshi

Aditya Joshi

129 Followers

I am a Software Engineer @Walmart and instructor @Udemy, working on Blockchain, and Kubernetes. I have completed CHFA, CKA, CKAD