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}}