效果图:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"time"
)
type Item struct {
Name string
Price int
}
func loginhanler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
r.ParseForm()
userName := r.FormValue("username")
pwd := r.FormValue("password")
if userName == "xxxxx" && pwd == "love" {
c1 := &http.Cookie{
Name: "username",
Value: userName,
MaxAge: 0,
HttpOnly: false,
}
http.SetCookie(w, c1)
fmt.Fprint(w, "登陆成功")
} else {
fmt.Fprint(w, "登陆失败")
}
} else {
t, err := template.ParseFiles("login.html")
if err != nil {
log.Fatal(err)
}
now := time.Now().Format("2006/01/02 15:04:05")
items := []Item{
{"iphone", 699},
{"ipad", 799},
{"iWatch", 199},
{"MacBook", 999},
}
data := map[string]interface{}{
"now": now,
"items": items,
}
t.Execute(w, data)
}
}
func userInfoHandler(w http.ResponseWriter, r *http.Request) {
username, err := r.Cookie("username")
if err != nil {
log.Fatal(err)
}
t, err := template.ParseFiles("user_info.html")
if err != nil {
log.Fatal(err)
}
t.Execute(w, username.Value)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/login", loginhanler)
mux.HandleFunc("/userinfo", userInfoHandler)
server := &http.Server{
Addr: ":8000",
Handler: mux,
}
err := server.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆页面</title>
</head>
<body>
<h1>欢迎登陆</h1>
<p>现在时间:{{.now}}</p>
<ul>
{{ range .items}}
<li>名称:{{.Name}} 价格:{{.Price}}</li>
{{end}}
</ul>
{{.comment}}
<form action="/login" method="post" enctype="application/x-www-form-urlencoded" novalidate autocapitalize="off">
<div>用户名
<input type="text" name="username">
</div>
<div>密码:
<input type="password" name="password">
</div>
<div>
<input type="submit" value="登陆">
</div>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
</head>
<body>
<h1>这是{{ . }}的个人中心页面!</h1>
</body>
</html>