This is the first part of a series of blog posts about embedding ReactJS front-end app with Go REST API back-end.
Let’s start first by creating a REST API in GO and Gin - a web framework for APIs written in GO.
Requirements
To get started, you need to install Go and Gin on your machine. You can follow the official instructions for installing Go here: https://golang.org/doc/install.
REST API Implementation
First, let’s initialize the application module with:
go mod init example/rest-and-react
To install Gin, you can use the go get command:
go get -u github.com/gin-gonic/gin
Next, you need to create a main.go
file in your project directory and import the gin package:
package main
import (
"github.com/gin-gonic/gin"
)
Then, you need to create a router object using the gin.Default()
function, which returns a new Gin instance with some default middleware:
func main() {
// Create a router object
router := gin.Default()
}
Now, you can define some routes for your API using the router.GET()
and router.POST()
methods. For example, let’s create a route for getting all users from a mock database:
// Define a user struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// Create a mock database
var users = []User{
{ID: 1, Name: "Alice", Email: "alice@example.com"},
{ID: 2, Name: "Bob", Email: "bob@example.com"},
{ID: 3, Name: "Charlie", Email: "charlie@example.com"},
}
// Define a handler function for getting all users
func getAllUsers(c *gin.Context) {
// Return the users as JSON
c.JSON(200, users)
}
Next, let’s register the route in main
function:
// Register the route for getting all users
router.GET("/users", getAllUsers)
Similarly, let’s create a route for creating a new user from a JSON request body:
// Define a handler function for creating a new user
func createUser(c *gin.Context) {
// Create a user variable to hold the request body
var user User
// Bind the request body to the user variable
if err := c.BindJSON(&user); err != nil {
// Return an error if the binding fails
c.JSON(400, gin.H{"error": err.Error()})
return
}
// Append the user to the mock database
users = append(users, user)
// Return the created user as JSON
c.JSON(201, user)
}
Next, let’s register the route in main
function:
// Register the route for creating a new user
router.POST("/users", createUser)
Finally, you need to run the router using the router.Run() method, which starts an HTTP server on port 8080 by default:
// Run the router
router.Run()
Just a reference, the final app should look like:
package main
import (
"github.com/gin-gonic/gin"
)
// Define a user struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// Create a mock database
var users = []User{
{ID: 1, Name: "Alice", Email: "alice@example.com"},
{ID: 2, Name: "Bob", Email: "bob@example.com"},
{ID: 3, Name: "Charlie", Email: "charlie@example.com"},
}
// Define a handler function for getting all users
func getAllUsers(c *gin.Context) {
// Return the users as JSON
c.JSON(200, users)
}
// Define a handler function for creating a new user
func createUser(c *gin.Context) {
// Create a user variable to hold the request body
var user User
// Bind the request body to the user variable
if err := c.BindJSON(&user); err != nil {
// Return an error if the binding fails
c.JSON(400, gin.H{"error": err.Error()})
return
}
// Append the user to the mock database
users = append(users, user)
// Return the created user as JSON
c.JSON(201, user)
}
func main() {
// Create a router object
router := gin.Default()
// Register the route for getting all users
router.GET("/users", getAllUsers)
// Register the route for creating a new user
router.POST("/users", createUser)
// Run the router
router.Run()
}
Finaly, let’s run the app.
go run .
In order to test it, you can use curl like me, or Postman. Let’s try with curl.
curl http://localhost:8080/users
[{"id":1,"name":"Alice","email":"alice@example.com"},{"id":2,"name":"Bob","email":"bob@example.com"},{"id":3,"name":"Charlie","email":"charlie@example.com"}]
You can create a new user by sending a POST request to http://localhost:8080/users with a JSON body:
curl -X POST -H "Content-Type: application/json" -d '{"id":4,"name":"David","email":"david@example.com"}' http://localhost:8080/users
{"id":4,"name":"David","email":"david@example.com"}
Documentation and links
- Gin documentation - https://github.com/gin-gonic/gin