Table of Contents
- Introduction
- Prerequisites
- Project Setup
-
Backend Development - Creating a REST API - Database Integration
- Frontend Development - Setting up React - UI Components
- Connecting Frontend and Backend
- Deployment
- 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:
- Create a new directory for your project:
$ mkdir go-react-app $ cd go-react-app - Initialize a Go module:
$ go mod init github.com/your-username/go-react-app - Create a
serverdirectory inside the project directory:$ mkdir server $ cd server - Initialize a new Go module for the server:
$ go mod init github.com/your-username/go-react-app/server - Create a
main.gofile in theserverdirectory:$ 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:
- Open the
main.gofile and import the required packages:package main import ( "encoding/json" "log" "net/http" ) - Define a
Userstruct to represent our data model:type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` } - 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) } - Set up the main server function to handle the API routes:
func main() { http.HandleFunc("/users", getUsers) log.Fatal(http.ListenAndServe(":8000", nil)) } - Start the server by executing the following command in the
serverdirectory:$ go run main.go - 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:
- Install the PostgreSQL driver for Go:
$ go get github.com/lib/pq - Update the
getUsersfunction 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) } - 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:
- Go back to the root project directory:
$ cd .. - Initialize a new React project:
$ npx create-react-app client - Change to the
clientdirectory:$ cd client - Start the React development server:
$ npm start - 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:
- Create a new file
Users.jsinside thesrcdirectory:$ touch src/Users.js - Add the following code to the
Users.jsfile: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; - Open the
src/App.jsfile 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; - Restart the React development server if it was not automatically restarted. Visit
http://localhost:3000and 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:
-
Open the
package.jsonfile in theclientdirectory. - Add the following line to the file, inside the
scriptssection:"proxy": "http://localhost:8000" -
Save the
package.jsonfile and restart the React development server. -
The frontend can now make API requests to the backend server without worrying about CORS issues. Update the server URL in the
getUsersfunction in themain.gofile to/usersinstead of the absolute URL. - 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:
- Build the React frontend by running the following command inside the
clientdirectory:$ npm run build - In the
main.gofile, 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)) } - Build and run the Go server:
$ go build $ ./server - Visit
http://localhost:8000to 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.