Your First REST API in Golang
Go was founded by 2 google Software Engineers. The main Purpose that Golang fulfills is it combines the best of two worlds Java and C++.
Prerequisites :
You Should be ideally using a Code Editor or IDE to write this API (Visual Studio Code, Sublime Text, Intellij, Atom, or any other)
You must have Go installed on your System. Below are the steps as specified on the Go website.
- Go download
- Go install
- Go code
Let’s deep dive directly into code!
1. Initialize Go Server:
Make a server.go
file in the root directory of your folder. The contents for the same are given below.
Do go get github.com/gorilla/mux
to install the mux package. We will be using mux as the HTTP router in this tutorial.
Below are the necessary imports, you will need in the implementation.
Now let’s code our main function, the entry point for the Rest API.
Now start the server by writing go run server.go
and hit the endpoint http://localhost:8000
on postman/browser.
Woohoo 💥💥, Congratulations your first Go server is up!
2. Setting up routes for adding and retrieving posts
we will be using a dummy database (an array) for the learning purpose. Let’s setup imports and our database in the server.
For getting all the posts from fake DB (Slice)
Add a post in the fake DB (Slice)
Now, you are almost there to test your server. But wait, we haven’t used routes.go
file anywhere. So the last step is to add the routes to the server.go file and link them with routers.
Add these two lines after / route
router.HandleFunc("/posts", routes.GetPosts).Methods("GET") router.HandleFunc("/posts", routes.AddPost).Methods("POST")
Finally your server.go
file should look like this:
And my friends, that's it! Let’s run our server again by typing the command in terminal go run main.go
Now you can test your simple REST API using postman/Insomnia. You can use this in your upcoming project while connecting it with a real Database.
If you are into GraphQL, checkout -
Here are my socials, in case you want to connect with me.