Building REST api with go using MUX

Building REST api with go using MUX

There are many libraries in Golang to create REST api. Out of these, Mux is very popular and stable library available to create REST api. In this article we will let you know how to create REST api’s using Mux

Project Setup and dependencies

As mentioned above, we are going to use mux library. So, go get the mux library using following command.

Create a file restapi.go and open it in any of your favorite text editor. Now, create basic rest api using following code.

Once you run this code, server starts on port 8080 however you can’t navigate as route points are not available yet.

Create Model

In go we use struct to create model. In this example we are using Emp with following variables

Add Endpoints

As discussed above, create endpoints

Data to support endpoints

In this example, we are using slice which contains following data to support endpoint.

Get All Emps

implement function GetEmps to return all employees as follow.

Get Employee based on id

Above endpoint returns all the employees available with the emps slice. In this function we will return the employee based on the id(from request)

Other EndPoints

Create a employee and delete employee based on id as follow

Complete Code

Now put together everything, the code will be like

Run the app

use go run restapi.go command to start the application.


Get All Employees

Get Employee by Id

Create Employee

Delete Employee

Download code Rest API Using MUX

Stay tuned for more updates and tutorials !!!


Leave a Reply

Your email address will not be published. Required fields are marked *