Building a Web Application with Go and React

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Project Setup
  4. Backend Development - Creating a REST API - Database Integration

  5. Frontend Development - Setting up React - UI Components
  6. Connecting Frontend and Backend
  7. Deployment
  8. Conclusion

Introduction

In this tutorial, we will explore the process of building a web application using the Go programming language for the backend and React for the frontend. By the end of this tutorial, you will have a basic understanding of how to create a web application from scratch, including setting up the backend server, creating REST APIs, integrating with a database, building the frontend interface, and connecting the frontend and backend together.

Prerequisites

Before starting this tutorial, it is recommended to have a basic understanding of Go and React. Familiarity with HTML, CSS, and JavaScript will also be helpful. Additionally, you will need to have the following software installed:

  • Go (>= 1.16)
  • Node.js (>= 12.0.0)
  • npm (>= 6.0.0)
  • PostgreSQL (>= 9.0)

Project Setup

To begin, let’s create a new directory for our project and set up the necessary folder structure:

  1. Create a new directory for your project:
     $ mkdir go-react-app
     $ cd go-react-app
    
  2. Initialize a Go module:
     $ go mod init github.com/your-username/go-react-app
    
  3. Create a server directory inside the project directory:
     $ mkdir server
     $ cd server
    
  4. Initialize a new Go module for the server:
     $ go mod init github.com/your-username/go-react-app/server
    
  5. Create a main.go file in the server directory:
     $ touch main.go
    

Backend Development

Creating a REST API

Now, let’s create a simple REST API using Go’s built-in net/http package:

  1. Open the main.go file and import the required packages:
     package main
        
     import (
         "encoding/json"
         "log"
         "net/http"
     )
    
  2. Define a User struct to represent our data model:
     type User struct {
         ID     int    `json:"id"`
         Name   string `json:"name"`
         Email  string `json:"email"`
     }
    
  3. Create an HTTP handler function to handle the route for fetching all users:
     func getUsers(w http.ResponseWriter, r *http.Request) {
         users := []User{
             {ID: 1, Name: "Alice", Email: "[email protected]"},
             {ID: 2, Name: "Bob", Email: "[email protected]"},
         }
        
         json.NewEncoder(w).Encode(users)
     }
    
  4. Set up the main server function to handle the API routes:
     func main() {
         http.HandleFunc("/users", getUsers)
        
         log.Fatal(http.ListenAndServe(":8000", nil))
     }
    
  5. Start the server by executing the following command in the server directory:
     $ go run main.go
    
  6. Open a web browser and visit http://localhost:8000/users. You should see the JSON response containing the users’ data.

Database Integration

In this section, we will integrate PostgreSQL as the database for our web application:

  1. Install the PostgreSQL driver for Go:
     $ go get github.com/lib/pq
    
  2. Update the getUsers function to fetch data from the PostgreSQL database:
     import (
         "database/sql"
        
         _ "github.com/lib/pq"
     )
        
     const (
         host     = "localhost"
         port     = 5432
         user     = "your-username"
         password = "your-password"
         dbname   = "your-dbname"
     )
        
     func getUsers(w http.ResponseWriter, r *http.Request) {
         connStr := fmt.Sprintf("host=%s port=%d user=%s "+
             "password=%s dbname=%s sslmode=disable",
             host, port, user, password, dbname)
        
         db, err := sql.Open("postgres", connStr)
         if err != nil {
             log.Fatal(err)
         }
         defer db.Close()
        
         rows, err := db.Query("SELECT id, name, email FROM users")
         if err != nil {
             log.Fatal(err)
         }
         defer rows.Close()
        
         users := []User{}
         for rows.Next() {
             var user User
             err := rows.Scan(&user.ID, &user.Name, &user.Email)
             if err != nil {
                 log.Fatal(err)
             }
             users = append(users, user)
         }
        
         json.NewEncoder(w).Encode(users)
     }
    
  3. Restart the server and visit http://localhost:8000/users. Now, the data will be fetched from the PostgreSQL database.

Frontend Development

Setting up React

Let’s set up the frontend of our application using React:

  1. Go back to the root project directory:
     $ cd ..
    
  2. Initialize a new React project:
     $ npx create-react-app client
    
  3. Change to the client directory:
     $ cd client
    
  4. Start the React development server:
     $ npm start
    
  5. Open a web browser and visit http://localhost:3000. You should see the default React welcome page.

UI Components

Now, we’ll create some UI components using React to display the users’ data fetched from the backend:

  1. Create a new file Users.js inside the src directory:
     $ touch src/Users.js
    
  2. Add the following code to the Users.js file:
     import React, { useEffect, useState } from 'react';
        
     function Users() {
         const [users, setUsers] = useState([]);
        
         useEffect(() => {
             fetch('/users')
                 .then((response) => response.json())
                 .then((data) => setUsers(data));
         }, []);
        
         return (
             <div>
                 <h1>Users</h1>
                 <ul>
                     {users.map((user) => (
                         <li key={user.id}>{user.name}</li>
                     ))}
                 </ul>
             </div>
         );
     }
        
     export default Users;
    
  3. Open the src/App.js file and replace the existing code with the following:
     import React from 'react';
     import Users from './Users';
        
     function App() {
         return (
             <div className="App">
                 <Users />
             </div>
         );
     }
        
     export default App;
    
  4. Restart the React development server if it was not automatically restarted. Visit http://localhost:3000 and you should see the list of usernames retrieved from the backend displayed on the screen.

Connecting Frontend and Backend

To connect the frontend and backend, we will proxy API requests from the React development server to the Go server:

  1. Open the package.json file in the client directory.

  2. Add the following line to the file, inside the scripts section:
     "proxy": "http://localhost:8000"
    
  3. Save the package.json file and restart the React development server.

  4. The frontend can now make API requests to the backend server without worrying about CORS issues. Update the server URL in the getUsers function in the main.go file to /users instead of the absolute URL.

  5. Restart the Go server and the React development server.

Deployment

To deploy the web application, we can build the React frontend and run the Go server on a production-level server:

  1. Build the React frontend by running the following command inside the client directory:
     $ npm run build
    
  2. In the main.go file, add the following code to serve the static files generated by the React build:
     import (
         "log"
         "net/http"
     )
        
     func main() {
         // ... existing code ...
        
         fs := http.FileServer(http.Dir("../client/build"))
         http.Handle("/", fs)
        
         log.Fatal(http.ListenAndServe(":8000", nil))
     }
    
  3. Build and run the Go server:
     $ go build
     $ ./server
    
  4. Visit http://localhost:8000 to see the deployed web application.

Conclusion

In this tutorial, we built a web application using Go for the backend and React for the frontend. We covered creating a REST API, integrating with a database, setting up React, creating UI components, and connecting the frontend and backend together. This tutorial only scratched the surface of what you can achieve with Go and React, but it provided a good starting point for building web applications. Keep exploring and experimenting to unleash the full potential of these powerful technologies.