Golang learning Web application construction based on Node.js
Golang Learning Web Application Building Based on Node.js
With the rapid development of Internet technology, Web applications are gradually becoming a key focus area for major enterprises and technical personnel. As a high-performance programming language, Golang is being sought after by more and more people. This article will introduce how to use Golang and Node.js to build a basic web application.
1. Environment preparation
Before you start building, you need to install the following two environments:
- Golang environment
Download the Golang installation package from the official website and configure GOPATH and GOROOT after installation.
- Node.js environment
Download the Node.js installation package from the official website. After installation, install the express, ejs, and body-parser modules through the npm command line tool. And install the MongoDB database.
2. Build the Web framework
- Initialize the template
In the Golang environment, initialize the template through the following command line:
go mod init {project_name}
{project_name} here is your project name. After executing this command, a go.mod file will be created, which needs to contain the following content:
module {project_name}
go 1.16
- Create the main application
In the project folder, create a main.go file, which is the entrance to the main application.
package main
import (
"github.com/gin-gonic/gin" "net/http" "log"
)
func main() {
router := gin.Default() router.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Hello World") }) err := router.Run(":8080") if err != nil { log.Fatal("服务器启动失败") }
}
here The gin framework is used as the web application framework, and the main code logic is to return the "Hello World" string through a GET request on the route. Finally, use the router.Run() function to start the web application and log if the startup fails.
- Create a static page
In the project folder, create a public folder to store static HTML files and other resource files. Create an index.html file in the public folder with the following code:
<head> <title>Golang学习之基于Node.js的Web应用程序搭建</title> </head> <body> <h1>Hello World</h1> </body>
- Create views
Create a views folder in the project folder to store EJS view files and other resource files. Create an index.ejs file in the views folder with the following code:
<head> <title>Golang学习之基于Node.js的Web应用程序搭建</title> </head> <body> <h1>Hello World</h1> <p><%= message %></p> </body>
- Create routes
Create a routes folder in the project folder to store routing files. Create an index.js file in the routes folder with the following code:
var express = require('express');
var router = express.Router();
/ GET home page. /
router.get('/', function(req, res, next) {
res.render('index', { message: '欢迎访问Golang学习之基于Node.js的Web应用程序搭建' });
});
module .exports = router;
Express is used as the web application framework. The routing function uses the res.render() function to render the EJS file and finally pass the message to the view file.
- Start the application
Create an app.js file in the project folder with the following code:
var express = require(' express');
var path = require('path');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/index' );
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use (bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public'))) ;
app.use('/', indexRouter);
app.listen(3000, function () {
console.log('Golang学习之基于Node.js的Web应用程序搭建已启动,端口为3000');
});
The Express framework is used here, the view engine is set to EJS, and port 3000 is listened to, and finally the app.listen() function is used to start the application.
The final project file structure is as follows:
project_name
├─go.mod
├─main.go
├─app.js
├─public
│ └index.html
├─routes
│ └index.js
└─views
└index.ejs
3. Connect to the database
- Install the MongoDB database
After installing the MongoDB database, connect to the database through the following command line:
mongo
- Create database
After connecting to the database, create a database through the following command line:
use {database_name}
where {database_name} is your database name.
- Create a collection
Create a collection in the database:
db.createCollection('{collection_name}')
here The {collection_name} is your collection name.
4. Processing requests and responses
- Processing POST requests
Add the following code in the index.js routing function to process POST requests:
router.post('/post', function(req, res, next) {
console.log(req.body); // do something
});
The body-parser middleware module is used here. This allows the data submitted in the POST request to be accessed through req.body in the routing function.
- Response to JSON data
Add the following code in the routing function to respond to JSON data:
router.get('/api', function(req, res, next) {
res.setHeader('Content-Type', 'application/json'); res.send({ message: 'Golang学习之基于Node.js的Web应用程序搭建', code: 0 });
});
The res.send() function provided by the Express framework is used here to respond to JSON data.
5. Summary
The above is the entire process of building a basic web application using Golang and Node.js. In this process, we used gin and Express frameworks, EJS view template engine, body-parser middleware module and other technologies. At the same time, we also connected to the MongoDB database and processed POST requests and JSON data responses. This provides basic support for our subsequent web application development.
The above is the detailed content of Golang learning Web application construction based on Node.js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.
