Getting Started with GoFr: Building a Simple Go API
When working with Go, setting up a microservice can involve a lot of repetitive things like handling HTTP routes, logging, database connections, and monitoring.
GoFr is an open-source framework for building HTTP microservices in Go. It provides some of these things out of the box, so we can focus more on writing the actual application.
In this article, I'll show how to create a small API using GoFr and run it locally.
🚀 Step 1: Create the Go Project
First, create a new folder for the project and move into it:
mkdir gofr-quickstart
cd gofr-quickstart
Now initialize a Go module:
go mod init gofr-quickstart
After that, install GoFr using:
`go get gofr.dev/pkg/gofr`
That's all we need for the initial setup.
💻 Step 2: Create the API
Create a file called main.go.
Add the following code:
package main
import (
"gofr.dev/pkg/gofr"
)
func main() {
app := gofr.New()
app.GET("/api/welcome", func(ctx *gofr.Context) (interface{}, error) {
return map[string]string{
"status": "success",
"message": "Welcome to GoFr Framework!",
}, nil
})
app.Run()
}
There isn't much code here.
First, gofr.New() creates the GoFr application. Then we use app.GET() to create a GET endpoint at /api/welcome.
The endpoint returns a simple map containing a status and a message.
Finally, app.Run() starts the server.
🏃 Step 3: Run the Application
Now run the application from the terminal:
go run main.go
The GoFr application starts the HTTP server, which runs on port 8000 by default.
We can now test the endpoint using curl:
curl http://localhost:8000/api/welcome
The response should look like this:
{
"data": {
"message": "Welcome to GoFr Framework!",
"status": "success"
}
}
You can also open the endpoint directly in your browser:
http://localhost:8000/api/welcome
🔥 Why GoFr?
One reason to use GoFr is that it handles some common microservice requirements without us having to build everything from scratch.
Some of the features include:
- Structured logging
- Health checks
- Metrics
- Database integrations
- Support for databases such as MySQL, PostgreSQL, Redis, and MongoDB
This can be useful when building Go services where you don't want to spend time setting up the same basic infrastructure for every project.
GoFr is also open source, so you can check out the source code and documentation on GitHub.
👉 https://github.com/gofr-dev/gofr
📌 Conclusion
In this tutorial, we created a small Go project, installed GoFr, added a GET endpoint, and ran the application locally.
The example is simple, but it gives you the basic idea of how routing works in GoFr. From here, you can start adding things like databases, authentication, more API endpoints, and other microservice functionality.
If you're just getting started with GoFr, this is a good small project to begin with before moving on to a larger service.
Top comments (0)