迷你mysql,迷你指南—与MySQL一起将REST API作为Go微服务构建

本文通过实例教程介绍了如何使用Go语言创建一个简单的REST API,并连接到MySQL数据库。我们将学习如何设置路由、数据库连接管理、并发数据库操作以及基本的数据库迁移。最后,还将构建Docker镜像,实现应用的部署和简化开发环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have recently found myself coding and deploying a lot of Go microservices, both at my day-job at Storytel and for my side-project Wiseer. In this mini-tutorial, I will create a simple REST-API with a MySQL database. The code for the complete project will be linked at the end of the article.

If you haven’t already done so I recommend taking the Go Tour as a complementary to this article.

Let’s dive in!

Setup the API

One of the first things to do is to choose a routing package. Routing is what connects an URL to an executable function. The mux package has served me well for routing, but there are other alternatives as well, with no real difference in performance. Such as httprouter and pat. I will be using mux in this guide.

For the sake of simplicity, we will create a single endpoint that prints out a message.

The code above creates a Router, associates a URL with an handler function — postFunction in our case — and starts a server on port 8080 using that Router.

Easy enough, huh? ????

Database connection

Let's build on the code above by connecting it to a MySQL database. Go provides an interface for SQL databases but requires a driver. I’m using go-sql-driver for this example.

The code is placed in another package, called db, and assumes there is a database running on localhost:3306 with a database called demo. The returned database automatically handles a connection pool to the database.

Let us update the postFunction from the previous code-snippet, to use this database.

That’s really it! It’s rather simple, but there are a few issues with the code above and a few nice-to-haves missing. This is where it gets a bit trickier, but don't jump ship just yet! ⚓️

Structs & Dependencies

If you’ve examined the code above, you might have noticed that we are opening the database on each API-call; even though the opened database is safe for concurrent use. We need some dependency management to make sure we only open the database once, for this, we want to use a struct.

We start by creating a new package, called app, to host our struct and it’s methods. Our App struct has two fields; a Router and a Database accessed at ln 17 and ln 24. We also set the returned status code manually at the end of the method at ln 30.

The main package and function also needs a few changes to make use of the new App struct. We remove the postFunction and setupRouter functions from this package, since it’s now in the app package. We are left with:

To make use of our new struct, we open a database and a new Router. Then we insert both of them into the fields of our new App struct.

Congratulations! You now have a connection to your database that will be used concurrently across all of your incoming API-calls ????

As a final step, we will add a GET-Method to our router setup and return the data in JSON. We start by adding a struct to fill our data with, and map the fields to JSON.

We follow that up with an expansion of the app.go file, with a new method getFunction that fetches and writes the data to the client response. The final file looks like this.

Database Migrations

We are going to add a final addition to the project. When a database is tightly coupled with an application or service you can save yourself unfathomable levels of headache by properly handling migrations of said database. We are going to use migrate for that, and expand our db package.

I'll go through the following, and admittedly long, gist below the embedded code.

Right after the opening of the database, we add another function call to migrateDatabase that will in turn; start the migration process.

We will also add a MigrationLogger struct to handle the logging during the process, the code can be seen here and it's usage on ln 45.

The migrations are executed from normal sql-queries. The migration files are read from the folder seen at ln 37.

Each time the database is opened, all the unapplied database migrations will be applied. Thereby keeping the database up to date without any manuainterventionon.

This coupled with a docker-compose file - containing the database - makes development on multiple machines dead-simple.

Wrapping it up

So you've made it all the way down here ???? ????

An undeployable microservice is of no use, therefore we will add a Dockerfile to package the application for easy distribution - then I promise to let you go.

The built image is a mere 10MB! ????

The code is available below.

go-microservice-api-template-simple

The code example from the article: are found in the folder rest-api.

I hope that you found this interesting and that you learned something! There are of course still things to improve upon, but that's where you and your creativity comes in ????

If you liked this article sharing it with friends or on Twitter is greatly appreciated!

99482de72739dda7a30b8a29c28b2c49.png

Johan Lejdung

@johanlejdung

ad0c7b03deabfe1a161345efb2d537eb.png

I just published this article of mine on dev.to

If you are interested in learning more about Go microservices, you should check it out! :)

dev.to/johanlejdung/a…

#golang #guide #tutorial #restapi #mysql #docker twitter.com/JohanLejdung/s…

20:27 PM - 11 Aug 2019

Johan Lejdung

@JohanLejdung

I wrote a thing! Check it out ???? https://t.co/ZM6araaN47 #golang #guide #tutorial #restapi #mysql #docker

twitter-reply-action.svg

twitter-retweet-action.svg

0

twitter-like-action.svg

0

I plan to cover more advanced topics in - hopefully shorter ???? - articles. The topics I have thought of so far are; middleware usage, testing, dependency injection and service layers.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值