用GO写一个网页代码,要有用户登录功能,包括用户名,密码输入框等
时间: 2023-06-04 16:07:39 浏览: 70
好的,那么我们可以使用 Go 语言的 net/http 包来创建一个简单的网页应用,实现用户登录功能。
首先,我们需要定义一个表示用户的结构体,包含用户名和密码字段:
```
type User struct {
Username string
Password string
}
```
然后,我们可以定义一个处理登录请求的函数,用于验证用户名和密码是否正确:
```
func loginHandler(w http.ResponseWriter, r *http.Request) {
// 解析用户名和密码
username := r.FormValue("username")
password := r.FormValue("password")
// 检查用户名和密码是否正确
if username == "admin" && password == "123456" {
// 登录成功,跳转到首页
http.Redirect(w, r, "/", http.StatusFound)
} else {
// 登录失败,显示错误信息
fmt.Fprintf(w, "用户名或密码错误!")
}
}
```
接下来,我们可以使用 Go 的 html/template 包来创建一个登录页面的 HTML 模板:
```
const loginTemplate = `
<html>
<head>
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="/login" method="post">
<label for="username">用户名:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">密码:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
`
```
最后,我们可以