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: