Go了

fango發表於2013-04-12

先有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了。

相關文章