Default Image

Months format

Show More Text

Load More

Related Posts Widget

Article Navigation

404

Sorry, the page you were looking for in this blog does not exist. Back Home

A guide on implementing Gorilla Mux within various packages in the Go programming language.

Introduction


In this tutorial blog, I will be explaining, How you can use Gorilla Mux in different packages in your code directory. For the construction of modern Golang web servers, Gorilla Mux is a strong HTTP router. It is a crucial Golang package for creating HTTP APIs and web applications. To show you how to utilize the Gorilla Mux in various packages while programming, I'll construct an API and explain the code. Before proceeding further, I would like to request you to kindly go through the prerequisites and be prepared with them for better understanding.


Gorilla Mux


Prerequisites


In this section, I have mentioned the required concepts which you need to be prepared with before proceeding with the blog. I recommend this so that you can get a clear picture of the concept that, I have explained in the blog. Therefore, the first thing you need to be prepared with is the basics of the Go Programming language and its syntax. The second obstruction, which you need to clear before proceeding is the HTTP Protocols. You should have a basic knowledge that how HTTP Protocol works. Next, you should be aware of concepts such as routing, middleware, and handling different HTTP Methods. Finally, you need to install a few basic software to proceed such as Go, PostMan (To test your API), and an IDE (I have used Visual Studio Code for my project).


After successfully, getting all prerequisites sorted, you are ready to get on this blog and put your hands on this project and learn something from it.


Creation of Project Directory


In this section, I will explain my project directory setup. To begin with, you need to open up your command prompt and input the first command i.e., “cd desktop”. This will navigate you to the desktop. Then, you need to create the directory with the help of the “mkdir Gin-Mux” command. The next step includes navigating to the directory of “Gin-Mux” for which you need to write “cd Gin-Mux”. These were the steps to create the directory for your project, now you need to install the mod file init. To install the mod file, the command you need to enter in the command prompt is “go mod init github.com/golangcompany/Gin-Mux” and right after this you can import the external packages that you need for this project i.e., Gorilla Mux and MongoDB. The commands you can use for these are “go get github.com/gorilla/mux” and “go get go.mongodb.org/mongo-driver/mongo”. These were the two important packages required to initialize your program. Now, let us proceed toward writing down the code by giving a “code .” command which will bring up the IDE on your screen with the directory already opened.


Structuring the Directory


In this section, I have mentioned the structure of the directory. You can figure it out by referring to image 1.


Gorilla Mux

Models & Database


I will begin with the struct now, as I feel starting with the struct is an easy way of structuring your program. My struct is going to be present in the models folder.


Gorilla Mux


To start with the basics, a struct is a user-defined data type that groups related data items together. For this project, I have two fields in my struct i.e., Name and Age. You can refer to Image 2 for the code.


Gorilla Mux

Gorilla Mux

Gorilla Mux

You can get more information about database setup on my other blog, How to Connect the Golang Application with MongoDB. I've mentioned the code's snap as a reference. Please see Images 3, 4, and 5.


Writing main.go


In the main.go file I have created a new router using the "mux" package and established an endpoint for handling HTTP requests. Here "/createuser" endpoint will handle the POST request and calls the "CreateUser" function from the "controller" package and finally, it starts the server using the "http.ListenAndServe" method with the address and the router. Please refer to image 6 for better clarification. It contains the code for the main.go file.


Gorilla Mux


Creating and setting up the controller

Gorilla Mux

Now, I will begin with the controller.go file. First, you need to mention the imports you want to use in the controller. Then create a function named “CreateUser”. Basically, "CreateUser" is a function that deals with creating new users. An "http.ResponseWriter" and a "*http.Request" are the two arguments that are being supplied to it. In order to parse the JSON data from the request body, it first constructs a new decoder. It then creates a new variable named "user" of type "models.User." The function then uses the decoder to attempt to decode the request body into the "user" variable. The function writes a "400 Bad Request" status code to the response and exits if there is a problem decoding the JSON. The user is then added to a MongoDB collection named "UserGinMux" from a package called "database" using the "InsertOne" function from the "mongo" package. Please refer to Image 8 for the rest of the code.

Gorilla Mux


As you can see, this function is a crucial part of the API and is responsible for creating new users in the system. It is designed to handle incoming HTTP POST requests to the "/createuser" endpoint, which is defined in the main function. This endpoint is where the JSON payload with the user information is sent and this function is responsible for parsing that JSON payload, validating the data, and inserting it into the MongoDB collection.


In order to test this function, I used Postman Application as it allows for easy testing of APIs. In the screenshot of the Postman Application, as you can see in Image 9, I have set up a POST request to the "/createuser" endpoint and passed in the JSON payload with the user information. The response from the server indicates that the user was created successfully and returns a "200 OK" status code. Additionally, to see the results in MongoDB Atlas, I also have taken screenshots of collections. as you can see in Image 10, it's showing the inserted users into the "UserGinMux" collection. This confirms that the user creation process is working as intended and data is being successfully stored in the database.


Overall, this blog provided an overview of the code and demonstrated how this function works in the context of the larger API. I hope that you found this information to be educational and that it helped you to understand the role of this function in creating new users in the system. If you are a Golang developer, make sure to stay informed by regularly reading relevant blogs and articles to continue learning and expanding your skills.

Gorilla Mux

Gorilla Mux