先有C:

echo 'main(){printf("Hi");}' > hi.c; gcc hi.c; ./a.out

后有Go:

echo 'package main;func main(){print("Hi")}' > hi.go; go build hi.go; ./a.out

中间的各种努力尝试不提也罢了。PC时代终结了。是时候挥别旧时的辉煌与灰心,翻开⋯

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", newPage)
    http.ListenAndServe(":1234", nil)
}

func newPage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello world", r)
}

⋯新的网页。

(sleep 1; open http://localhost:1234) & go run hello.go

试试模版:

package main

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

func main() {
    http.HandleFunc("/", newPage)
    http.ListenAndServe(":1234", nil)
}

func newPage(w http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.New("page").Parse(page))
    tmpl.Execute(w,  r.URL.Path)
}

const page = `
<h1>Hello {{.}}!</h1>
`

试着直接上 index.html:

package main

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

func main() {
    http.HandleFunc("/", newPage)
    http.ListenAndServe(":1234", nil)
}

func newPage(w http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.New("page").ParseFiles("index.html"))
    tmpl.Execute(w,  r.URL.Path)
}

空白!白色恐怖!为什么没有载入! 仔细再看一遍http://localhost:6060/pkg/text/template/#ParseFiles,不得其解。

搜索!https://groups.google.com/forum/?fromgroups=#!searchin/golang-nuts/parsefiles/golang-nuts/CTRWmsg5ofw/Lz2sXilaPSIJ。原来是个细节没搞清楚。改:

tmpl.ExecuteTemplate(w, "index.html", r.URL.Path)

或者

tmpl := template.Must(template.New("index.html").ParseFiles("index.html"))

或者直接

tmpl := template.Must(template.ParseFiles("index.html"))

都可以。是模版的名字搞错了。Go了。