Home  >  Article  >  Backend Development  >  Can golang write web pages?

Can golang write web pages?

PHPz
PHPzOriginal
2023-05-10 09:10:06715browse

With the continuous development of Web technology, web pages have become an important information dissemination and interaction tool. In this process, various technologies were also born, including the rise of server-side JavaScript languages ​​such as SNode.js.

However, many developers may be curious, can golang, a language used for back-end development, be used to write web pages? The answer is yes. In this article, we will introduce how golang supports web development, as well as the methods and precautions for using golang to write web pages.

  1. golang supports Web development framework

Like other lower-end languages, golang itself is not a language specifically used for Web development, but it can cooperate with Web frameworks Used for web development. The following are some common golang web frameworks:

1.1 Gin

Currently, Gin has become the preferred web framework for many golang developers. It has the following characteristics:

  • Simple structure, easy to learn and use
  • High performance, much faster than net/http
  • Supports middleware, easy to expand
  • Provide RESTful API support
  • Provide excellent documentation and community support

1.2 Beego

Beego is an enterprise-level web application framework. Its characteristics are different from Gin:

  • Contains many components and functional modules, supports common features such as ORM, MVC, etc.
  • Provides many command line tools and supports automation Deployment and testing
  • Supports multiple languages ​​and can support international applications

1.3 Revel

Revel is written in golang relying on Netty (a high-performance web server) Web framework has the following characteristics:

  • Supports RESTful architecture
  • Integrated ORM framework
  • Supports hot loading to speed up the code debugging and deployment process

The different characteristics of the above three web frameworks can meet the needs of different types of web applications, and developers can choose according to their actual needs.

  1. How to write web pages in golang

After understanding the golang Web framework, we can start to learn how to use golang to write web pages. The following are some relatively simple methods of writing web pages in golang.

2.1 Basic Edition

The following code shows how to create a simple web server and HTTP handler in golang's standard library.

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello World")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Visit http://localhost:8080/ on the browser, you will see the output "Hello World". Although simple, this is also a basic web page that can display a fixed message. You can output other information by modifying the content of fmt.Fprint(w, ...) in the handler function.

2.2 Template version

If you want to generate more complex html pages, you can use golang templates. Golang's standard library contains corresponding packages, which can be used easily.

There are two ways:

1. Use the text/template package

package main

import (
    "html/template"
    "log"
    "net/http"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        p := Person{"Amy", 20}
        tmpl, err := template.New("").Parse(`
            <html>
                <head>
                <title>Hello World</title>
                </head>
                <body>
                <h1>Hello World!</h1>
                <ul>
                    <li>Name: {{.Name}} </li>
                    <li>Age : {{.Age}} </li>
                </ul>
                </body>
            </html>
        `)
        if err != nil {
            log.Fatalf("Failed to parse template: %v", err)
        }
        if err := tmpl.Execute(w, p); err != nil {
            log.Printf("Failed to execute template: %v", err)
        }
    })

    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatalf("Failed to listen and serve: %v", err)
    }
}

In this example, we define a Person structure for passing data. In the processing function, an html page is generated through the text/template package and the Name and Age of the Person are output. Visit http://localhost:8080/ in the browser and see the output results.

2. Use the html/template package

package main

import (
    "html/template"
    "log"
    "net/http"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        p := Person{"Amy", 20}
        tmpl, err := template.ParseFiles("views/index.html")
        if err != nil {
            log.Fatalf("Failed to parse template: %v", err)
        }
        if err := tmpl.Execute(w, p); err != nil {
            log.Printf("Failed to execute template: %v", err)
        }
    })

    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatalf("Failed to listen and serve: %v", err)
    }
}

Same as the above example, we define a Person structure. In the processing function, the html/template package is used to generate an html page, but in this example we use the ParseFiles function to read an html file for template parsing. This approach is more modular and will make later maintenance more convenient.

  1. Using third-party template packages

It is quite troublesome to use the templates in the golang library above because you need to hand-write the template code, but if you use the third-party template package directly , which can avoid hand-written html code.

The following demonstrates the use of third-party template package "https://github.com/gobuffalo/plush":

3.1 Installation

Install dependency packages

go get github.com/gobuffalo/plush

3.2 Write template

In the root directory, create the views/index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>golang html demo</title>
</head>
<body>
    <div>
        <span>Name: {{.Name}}</span>
        <p>Age: {{.Age}}</p>
    </div>
</body>
</html>

3.3 Write the processing function

func handler(w http.ResponseWriter, r *http.Request) {
    p := map[string]interface{}{"Name": "Robert", "Age": 23}
    t, err := plush.RenderFile("views/index.html", p)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        w.Write([]byte(fmt.Sprintf("Error rendering template: %s", err)))
        return
    }
    w.Write([]byte(t))
}

In the root directory Next, create a main.go file and write the code.

  1. Notes

When developing using the golang Web framework, you need to pay attention to the following points:

4.1 Goroutine concurrency features

Golang uses goroutine to achieve concurrency, which is also one of the features of the golang language. However, in the development of web frameworks, you need to pay attention to using correct concurrency methods to avoid resource conflicts and competition issues. Lock technology and channel technology can be used for control. Lock technology is mainly to protect shared data, while channel technology is to coordinate the interaction between multiple coroutines.

4.2 Introducing other libraries

When using golang to write and develop web applications, we sometimes need to introduce third-party libraries to enhance our applications. Before using these libraries, their code and performance need to be carefully checked to ensure the reliability and stability of the application.

4.3 Debugging

In the process of web application development, debugging is an inevitable part. To enhance the readability and scalability of code during code debugging, you can use system tools such as log to provide prompts. The golang standard library also provides tools like web/httptest.

  1. Conclusion

In general, although the main difference between the golang Web framework and other frameworks is concurrency processing, it has strong performance and simplicity. By using the golang web framework, you can improve efficiency and stability when developing web applications. By using golang to write web pages, both application scenarios and code efficiency can make it easier for developers to realize their ideas. Specifically, we can use the standard library, third-party template packages, and other libraries, paying attention to the noted caveats.

The above is the detailed content of Can golang write web pages?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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