Implementing simple web applications based on Go language

Table of contents

  • Preface
  • Go language features
  • Written before using Go language to implement web applications
  • Create web server
  • Declare a structure operation
  • Add the use of middleware
  • Use a static file server
  • at last

Preface

Among programming languages, several new languages ​​that have come out in recent years are very good, such as Go, Python, Rust, etc. Among them, Go language (Golang), as an open source, statically typed, fast, reliable and concise programming language, has gradually become a popular choice for web development and is increasingly favored by developers. So this article will briefly share how to implement a simple Web application through Go language, and summarize the usage experience. Starting from environment construction, it will gradually implement routing processing, template rendering, database connection and other functions to help readers understand the role of Go language in Applications in web development.

Go language features

Let’s first understand the characteristics of the Go language. According to the official introduction, the characteristics of the Go language are: concise syntax, easy to learn, and flat learning curve; unified code style, good execution performance, and high development efficiency; the built-in garbage collection mechanism of the Go language allows It has the same development efficiency as Python, PHP and other languages, and supports concurrency.

Moreover, the Go language has great advantages in creating simple and efficient Web servers and applications. The Go language provides a built-in HTTP package, which contains the practical tools needed to quickly create a Web or file server. This makes it possible to use the Go language to create a Web Servers and web applications become simple and efficient.

Written before using Go language to implement web applications

Before starting to use the Go language to implement Web applications, I need to say a few more words. Readers who have used the Go language must know that most of the uses of Go are run in the terminal, or run in the installed environment. Good environment. If a new developer does not install the Go language environment, he will not be able to run the Go language program he writes, so this requires the new developer to first build his own local Go program running environment. It is very simple to build a Go development environment. Go directly to the Go official website to download the corresponding image. Here we take the Windows operating system as an example and enter the official download linkAll releases - The Go Programming Language Find the download package for Windows operating system and download it directly.

After the download is successful, directly open the downloaded installation program, that is, the .msi file, and then perform the installation operation according to the installation wizard, which will not be detailed here.

After successful installation, check and verify the Go installation. Directly open the Windows command prompt, which is the Mac terminal, and enter the following command line to verify:

go version

After the running environment is set up, you can start to implement the web application. Here is the specific implementation of the editor using VS Code. Then you need to install an extension plug-in that supports the Go language in VS Code, as shown below:

After installation, choose to use the Gin framework when creating a new Go program. This framework is said to be very easy to use. For the specific method of installing the GIN framework, you can directly use Go’s official package management tool go get to install:

go get -u github.com/gin-gonic/gin

After installing GIN, since the VS Code editor does not have the function of creating a new project, you need to create a new file yourself first:

Then open this folder through the VS Code editor, open the posture: click File in VS Code --> Open Folder, then select the newly created folder, and then create a new file with the suffix .go in the file, and build main here .go file, as shown below:

After opening the folder, click New File.

Then open the terminal option at the bottom of the VS Code editor, and then enter the command line in the terminal: go mod init go_web and press Enter.

Writing this means that all preparations for implementing web applications using Go language are completed.

Create web server

Find the mian.go file created above, and then add the following code to the file:

package main
import (
    "github.com/gin-gonic/gin"
)
func main() {
    r := gin.Default()
    r.GET("/", func(c * gin.Context) {
        c.JSON(200,gin.H{
            "message":"hello go”,
        })
    })
    r.Run()  // listen and serve on 100.12.78.0:8080
 }

The above code implements a simple Web service, using gin's Default() function to create a default gin instance. r.GET() is to register the get request route, and the r.Run() function is to start the service.

Declare a structure operation

Since request parameters and response data need to be classified and processed in actual situations, it is necessary to declare and define a structure to represent the request and response. Also continue to add code in the newly created mian.go file, as shown below :

type Reque struct {
    Name string `json: "name"  binding:"required"`
}
type Respon struct {
    Message string `json: "message"`
}
func main() {
    r := gin.Default()
    r.POST("/", func(c *gin.Context) {
    var req Reque
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    res := Respon{Message:"hello "+ req .Name}
    c.JSON(http.StatusOK, res)
    })
    r.Run() // listen and serve on 100.12.78.0:8080
}

In the above code, two structures Reque and Response are defined. Reque contains a name field to represent the user name in the request; Response contains a message field to display the response message. In the r.POST() function, use the c.ShouldBindJSON() function to bind the request data to the Reque structure. If the request is abnormal, a 400 error will be returned. If the request is successful, a name response message will be returned.

Add the use of middleware

In the application, middleware needs to be used to process request-related content, such as processing request headers and performing authentication processing. Then the Logger() middleware built in the gin framework is used, which is still in the newly created mian.go file. Continue adding code as shown below:

func main() {
    r := gin.New()
    r.Use(gin.Logger())
    r.POST("/",func(c *gin.Context) [
        var req Reque
        if err := c.shouldBindJsON(&req); err != nil {
            c.JSON(http.statusBadRequest, gin.H{"error": err.Error()})
            return
         }
        res := Response{Message: "hello"  + req.Name}
        c.JSON(http.StatusOK, res)
    })
    r.Run() // listen and serve on 100.12.78.0:8080
 }

The above is to create a new gin instance and use gin's built-in Logger() middleware. This middleware will record detailed logs of each request to facilitate problem discovery.

Use a static file server

When building a web application, it is inevitable not to use some static resources, such as pictures, scripts, etc., which requires a static file server. The built-in static file processing middleware of the gin framework is still used here, and is still modified in the newly created mian.go file. The code is as follows:

func main() {
    r := gin.New()
    r.Use(gin.Logger())
    r.LoadHTMLGlob("template/*")
    r.Static("/static", "./public")
    r.GET("/", func(c * gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{})
    })
    r.Run()  // listen and serve on 100.12.78.0:8080
 }

What is used here is to load the HTML front-end template into the program through the r.LoadHTMLGlob() function, then use the r.Static() function to map all static resource files in the public directory to the /static route, and finally use r. The c.HTML() function is used in the GET() request function to return the HTML front-end template to the user.

at last

Through the above specific implementation process of implementing a simple web application based on the Go language, we can see that the gin framework of the Go language is very easy to use and can quickly build a simple and easy-to-use web application. Starting from setting up the environment, to splitting the specific implementation processes and steps, as well as the use of specific functions, readers must have easily learned how to use Go language to implement web applications. It should be noted that what this article introduces is only a relatively simple example. I hope it can bring some inspiration to readers. If readers need to learn more about the development and use of the Go language, please go to the Go official website for in-depth learning. In addition, this article shares The example is relatively simple, so please forgive me if you have any questions related to the Go language. If you have any questions, please leave a message in the comment area. Thank you for watching!

Guess you like

Origin blog.csdn.net/CC1991_/article/details/134792614