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认识的路径,所以图片的位置也设置了路由,见http.ServeFile方法,并注意html设置的图片路径。