Golang learning Web application construction based on Node.js

王林
Release: 2023-06-24 09:34:24
Original
1049 people have browsed it

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:

  1. Golang environment

Download the Golang installation package from the official website and configure GOPATH and GOROOT after installation.

  1. 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

  1. 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

  1. 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"
Copy after login

)

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("服务器启动失败")
   }
Copy after login

}

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.

  1. 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> 
Copy after login

  1. 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>
Copy after login

  1. 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应用程序搭建' });
Copy after login

});

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.

  1. 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');
Copy after login

});

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
Copy after login

3. Connect to the database

  1. Install the MongoDB database

After installing the MongoDB database, connect to the database through the following command line:

mongo

  1. 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.

  1. 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

  1. 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
Copy after login

});

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.

  1. 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 });
Copy after login

});

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!