主页 M

golang web应用cookie实现登陆

2022-10-20 网页编程网 网页编程网

main.go

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) {
    // 如果是post请求,注意先后顺序
    if r.Method == http.MethodPost {
        // 解析表单 并且校验
        r.ParseForm()
        userName := r.FormValue("username")
        pwd := r.FormValue("password")

        // 如果输入正确,则发送cookie 并给出反馈
        if userName == "123" && pwd == "love" {

            c1 := &http.Cookie{
                Name:     "username",
                Value:    userName,
                MaxAge:   0,
                HttpOnly: false,
            }

            http.SetCookie(w, c1)

            //fmt.Fprint(w, "登陆成功")//fmt Header只能输出一个
             
        //      w.Header().Set("Cache-Control", "must-revalidate, no-store")
         //        w.Header().Set("Content-Type", " text/html;charset=UTF-8")
         //w.Header().Set("Location", "http://wap.baidu.com/")//??????
             w.Header().Set("Location", "/userinfo")
            w.WriteHeader(307)//the key when redict

        } 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)
    }
}

// 拿到cookie,并且显示出来,说明登陆成功
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)
    }
}

2.login.html

<!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>

3.user_info.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
</head>
<body>
<h1>这是{{ . }}的个人中心页面!</h1>
</body>
</html>
阅读原文
阅读 1529
123 显示电脑版