Home > Article > Backend Development > 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:
Download the Golang installation package from the official website and configure GOPATH and GOROOT after installation.
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
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
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.
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:
8b05045a5be5764f313ed5b9168a17e6
100db36a723c770d327fc0aef2ce13b1
<head> <title>Golang学习之基于Node.js的Web应用程序搭建</title> </head> <body> <h1>Hello World</h1> </body>
73a6ac4ed44ffec12cee46588e518a5e
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:
8b05045a5be5764f313ed5b9168a17e6
100db36a723c770d327fc0aef2ce13b1
<head> <title>Golang学习之基于Node.js的Web应用程序搭建</title> </head> <body> <h1>Hello World</h1> <p><%= message %></p> </body>
73a6ac4ed44ffec12cee46588e518a5e
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.
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
After installing the MongoDB database, connect to the database through the following command line:
mongo
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 in the database:
db.createCollection('{collection_name}')
here The {collection_name} is your collection name.
4. Processing requests and responses
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.
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!