Home Backend Development Golang Golang learning Web application construction based on Node.js

Golang learning Web application construction based on Node.js

Jun 24, 2023 am 09:34 AM
nodejs golang web application

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

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 pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

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.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

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.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

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.

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

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

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

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

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

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.

Golang framework development practical tutorial: FAQs Golang framework development practical tutorial: FAQs Jun 06, 2024 am 11:02 AM

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.

See all articles