package main
import (
"fmt"
"html/template"
"log"
"net/http"
)
func login(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
if r.Method == "GET" {
t, err := template.ParseFiles("html/login.html")
if err != nil {
fmt.Fprintf(w, "parse template error: %s", err.Error())
return
}
t.Execute(w, nil)
} else {
username := r.Form["username"]
password := r.Form["password"]
fmt.Fprintf(w, "username = %s, password = %s", username, password)
}
}
func main() {
http.HandleFunc("/html/pics/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
http.HandleFunc("/login", login)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
主要是注意顯示圖片的路徑,不能是原來的html的路徑,必須是go認(rèn)識的路徑,所以圖片的位置也設(shè)置了路由,見http.ServeFile方法,并注意html設(shè)置的圖片路徑。