Originally used the Go language to write a Web program (ii)

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

In the previous section, we wrote a Web service port listener and a simple URL request output using the Go language, but did not implement the colorful HTML pages we saw when we were surfing the web, and when we needed to add separate HTML pages to the services written by the Go language, We need to import html/template in the service program.

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

Then we create a template file, named index.html in the Main.go same folder, the file is filled with the following code:

Main.go fill in the following code:

package mainimport ("fmt""html/template""log""net/http")func IndexHandler(w http.ResponseWriter, r *http.Request) {t, err := template.ParseFiles("index.html")if err != nil {log.Println(err)}err = t.Execute(w,nil)if err != nil {log.Println(err)}}func main() {    http.HandleFunc("/index",IndexHandler)fmt.Println("服务端口:8000")                 //控制台输出信息err := http.ListenAndServe(":8000", nil) //设置监听的端口if err != nil {log.Fatal("ListenAndServe: ", err)}}

When you run go run main.go to access http://localhost:8000/index using your browser, you get the following results:

Related Article

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.