Go language learning: Dynamic Web

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Use template templates in Golang to implement Dynamic Web in HTML.

1. Network Port monitoring operation:

Web Dynamic pages use Http.handlefunc () instead of HTTP. Handle ()

The main function implementation code is as follows:

Func main () {http. Handlefunc ("/info", Infohandler) Err: = http. Listenandserve (": 9090", nil) if err! = Nil {log. Fatal ("Listenandserve:", err.) Error ())}}


2. Use of template templates:

The first thing to do is insert fields in HTML for Golang to use. Golang template passed {{.}} To include the field that was replaced at render time, {{.}} Represents the current object, which is similar to this in Java or C + +, if you want to access the field of the current object through {{. Data}}, but note that this field must be exported (the field letter must be in uppercase), otherwise it will be rendered with an error.

Golang Instance Code:

<span style= "FONT-SIZE:12PX;" >type infromation struct{name string}</span>

HTML code:

Switch.html

<!doctype html>

3. Respond to the page,

Create a template First

Func parsefiles (filenames. String) (*template, error)

Then fill in the fields and implement the template

Func (t *template) Execute (WR io. Writer, Data interface{}) error

In the function, the second parameter, data, fills in the field to be implemented.

The relevant code is as follows

Func Infohandler (w http. Responsewriter, R *http. Request) {info: = new (infromation) if R.method = = "GET" {info. Name = "A" T, err: = template. Parsefiles ("switch.html") if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) Return}t.execute (W, info) return} if R.method = = "POST" {  fmt. Println ("click") info. Name = "B" T, err: = template. Parsefiles ("switch.html") if err! = Nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) Return}t.execute (W, info) return}}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.