Go实现简易的Web登陆交互

效果图:

Go实现简易的Web登陆交互_第1张图片

  • 源代码
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 == "lizhisheng" && 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)
	}

}

// 拿到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)
	}

}

  • 登陆页面: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>
  • 个人中心页面:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户信息</title>
</head>
<body>

<h1>这是{{ . }}的个人中心页面!</h1>

</body>
</html>

你可能感兴趣的:(Go)