我需要go语言代码,编写一个静态Dashboard页面,并能够和mysql数据库中的用户表进行交互。与后端数据库中用户表匹配后跳转。
时间: 2024-03-28 17:37:36 浏览: 72
以下是一个简单的示例代码,希望对您有所帮助:
1. 后端:
```go
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
_ "github.com/go-sql-driver/mysql"
"github.com/gin-gonic/gin"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Password string `json:"password"`
}
func main() {
db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/test")
if err != nil {
log.Fatal(err)
}
defer db.Close()
router := gin.Default()
router.GET("/users", func(c *gin.Context) {
var users []User
rows, err := db.Query("SELECT id, name, password FROM user")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer rows.Close()
for rows.Next() {
var user User
if err := rows.Scan(&user.ID, &user.Name, &user.Password); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
users = append(users, user)
}
c.JSON(http.StatusOK, users)
})
router.GET("/user/:id", func(c *gin.Context) {
id := c.Param("id")
var user User
err := db.QueryRow("SELECT id, name, password FROM user WHERE id=?", id).Scan(&user.ID, &user.Name, &user.Password)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, user)
})
router.POST("/user", func(c *gin.Context) {
var user User
if err := c.BindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
_, err := db.Exec("INSERT INTO user (name, password) VALUES (?, ?)", user.Name, user.Password)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "User added successfully"})
})
router.Run(":8080")
}
```
2. 前端:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<form>
<label for="userId">User ID:</label>
<input type="text" id="userId" name="userId">
<input type="button" value="Submit" onclick="getUser()">
</form>
<div id="userInfo"></div>
<script>
function getUser() {
var userId = document.getElementById("userId").value;
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/user/" + userId);
xhr.onload = function () {
if (xhr.status === 200) {
var user = JSON.parse(xhr.responseText);
var userInfo = document.getElementById("userInfo");
userInfo.innerHTML = "ID: " + user.id + "<br>" +
"Name: " + user.name + "<br>" +
"Password: " + user.password;
} else {
alert("Error: " + xhr.statusText);
}
};
xhr.onerror = function () {
alert("Network Error");
};
xhr.send();
}
</script>
</body>
</html>
```
3. 数据库:
在mysql数据库中创建用户表,可以使用以下命令:
```sql
CREATE TABLE user (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
```
以上代码仅供参考,可能需要根据具体的需求进行修改和调整。
阅读全文