Building A Simple API Server Using httprouter in Golang
Discussing:
- Dependency management using Go Dep
- Setting up API endpoint using httprouter
- Mocking http request handler for testing
- Identify issues I stumbled upon and how I had them fixed.
Dependency management using Go Dep
Go Dep is a dependency management tool for Go. It requires Go 1.9 or newer to compile. For installation, you can visit here
Running dep init in the project’s root directory creates two files, a directory and scans the root directory to check if there’s any .go file in the root directory, and downloads all the packages needed for the project into the vendor folder.
Gopkg.toml Gopkg.lock vendor/If we want to add a new dependency, all we need to do is:
dep ensure -add github.com/julienschmidt/httprouterThat adds httprouter to the project’s dependencies.
Setting up API endpoint using httprouter
First, we create a Logger function which wraps around the handler function to print log messages before and after execution of the handler function:
Then we setup our response and error helpers. You can check them out here:
Response:
Error:
Now that we have our Logger, Response and Error helpers. Let’s go ahead and implement the Model.
User Model
What did we do here:
- We created a
missingFieldErrorstring type for handling errors - We created a user struct for storing user’s information and specify the
json keyfor each field. - Create a receiver function for validating user struct.
- Create a global variable for storing created user
- A
GenerateUserIDfunction for incrementing user’sID
Router
What do we have here?
Get ابوبخر اولاديجي ✪’s stories in your inbox
Join Medium for free to get updates from this writer.
We have a Route of type struct which contains:
- Name :- Name of the route
- Method :- Method the route accepts i.e POST, GET, PUT etc.
- Path :- The endpoint to reach the API
- Handler Function :- The function for handling the HTTP request
And also, we have a function NewRouter which accepts an Array of Route [Route] and returns nil if routes array is empty, and if not, attach each route to the Logger function before registering the route so as to handle the HTTP requests.
User API
This is the User Create Request Handler Function.
We created an interface which helps validating any type that implements it. Just as we did in the user.go file.
In the create user http request handler function, we decode the user model which makes use of the decode function which takes Request and any type that conforms to the interface ok. Which is then used to verify the body of the request isn’t null, the decoder doesn’t throw any error when decoding the request body.
Once decoded, and with no error, we store the value, and create the user.
main.go
In our main.go file, we bring everything together.
Mocking http request handler for testing
Here, we have a function that takes in the following:
- Request: A http package struct for handling requests
- Method: Request method
- Path: Request path
- reqHandler: A httprouter Handle function
And it returns a httptest response recorder ResponseRecorder is an implementation of http.ResponseWriter that records its mutations for later inspection in tests.
In the function, an instance of httprouter is created and configured. We create a recorder and implement the handler interface.
Identify issues I stumbled upon and how I had them fixed.
Some of the known issues experienced are:
- Ensured body isn’t nil before reading from it.
- Have a receiver function for validating decoded user
- Generating new user id once a new user is created
Conclusion
This is just a basic implementation of how to make use of httprouter for handling HTTP Requests there’s no Database, Authentication or security involved. In the next article, I’ll be writing more about Contexts. Enjoy.
Thank You








