Building RESTful web API service using Golang, chi, and MySQL

create your very first REST API using go



In this API, We’ll use dep for dependency manager, Mysql as database work and chi package for routing. It’s a good practice to add a package manager to your project. We’ll use chi package for routing because of its middleware and some good features. You can go through their doc.

In generic CRUD application, API as follows:
  1. POST /posts
  2. GET /posts
  3. GET /posts/{id}
  4. PUT /posts/{id}
  5. DELETE /posts/{id}

Before starting, make sure your $GOPATH works fine. Then go to $GOPATH/src and make a directory named wiki. install required packages:
go get github.com/go-chi/chi
github.com/go-sql-driver/mysql

Now create main.go inside wiki directory. Import chi and SQL package in main.go like bellow. Create all router and DB connection credential. I’ve put my own you can change it according to yours.

Pretty neat ahh !. Well, Let’s set up a connection with DB and initialise router and middleware. here, We’ll use recover middleware. Because if any request fails, your app won’t die, you can request again without restarting your app.

Don’t panic about catch function I’ll define this function later. dbSource fullest form is username:password@protocol(address)/dbname?param=value

Now we’ll create a basic POST model which is used for send and retrieve data. In go, a struct can typically serve as your model schema.

By adding json tag we can marshalled our struct to JSON. This minute, we will create go-mysql-crud database and posts table on MySQL DB from terminal or third-party app. I mostly use sequel pro.
Can you remember about the routes and handle function we created earlier? It’s time to implement those. When someone request /posts by using POSTmethod with title and content json data, It’ll be executed CreatePost function.

In the above code, we’ve used json.NewDecoder to catch POST data from parameter `r ` and decoded it into our struct post model. Then prepare our insert query and execute the query after that.

title=? means we have dynamic title data to execute which we will retrieve from post variable. Don’t forget to close your query. Lastly we send our message in JSON format to the client using respondwithJSON func. We’ll implement it shortly.

Let’s implement the UpdatePost and DeletePost function.

To catch id I usechi.URLParam . Try to implementAllPostandDetailPost. If you need help then visit github repo.You can find full code over there.

Running this example will spin up a server on port 8005 and can be accessed at http://localhost:8005. (Logger function print the log in your every request on the terminal and it is implemented on helper.go file below.)

We will split main.go to helper.go for including our helper function. You can also split the router and move the router function to router.go.

helper.go
Okay, Can we run our code now? In github repo I’ve included a makefile which can help us to save our time for every time building the app.

If you include makefile in your code directory then run
make run

If you don’t then build the main.go
go build .

It’ll create a binary file in your directory and to run this command $./wiki as our directory name is wiki. So far, Our app is running and serve 8005 port.

To test the API open postman and run those route sequentially. For instance -

for creating post
for creating post

Yee! We’ve finished our mundane tasks. Again, you can find full source code from github repo. I also added docker and docker-compose file over there.

Never miss a post from Chris Gregori, when you sign up for Ednsquare.