我需要go语言完整代码来编写两个静态Dashboard页面,并能够和mysql数据库中的user表,contain表进行交互。第一个页面中首先需要输入user表的用户id,用户名,cpu限制,内存限制,磁盘容量限制,然后跳转至第二个页面,这个页面能够展示用户id所匹配的contain表中所有所包含的contain的contain的id,contain是否在运行,最后一次更新的时间,所需要的镜像id,占用的cpu核数,占用内存大小,暴露的端口号及所需镜像的打包时间的信息并能够对记录进行增删改查
时间: 2024-03-27 12:41:30 浏览: 67
好的,以下是一个简单的示例代码,供你参考:
```go
package main
import (
"database/sql"
"fmt"
"html/template"
"log"
"net/http"
_ "github.com/go-sql-driver/mysql"
)
type User struct {
ID int
Username string
CPULimit int
MemoryLimit int
DiskCapacity int
}
type Contain struct {
ID int
UserID int
IsRunning bool
LastUpdated string
ImageID string
CPUUsage int
MemoryUsage int
ExposedPort int
ImagePackTime string
}
func main() {
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database_name")
if err != nil {
log.Fatal(err)
}
defer db.Close()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
tmpl := template.Must(template.ParseFiles("templates/index.html"))
tmpl.Execute(w, nil)
return
}
userID := r.FormValue("userID")
username := r.FormValue("username")
cpuLimit := r.FormValue("cpuLimit")
memoryLimit := r.FormValue("memoryLimit")
diskCapacity := r.FormValue("diskCapacity")
// Insert user record into database
_, err := db.Exec("INSERT INTO user (id, username, cpu_limit, memory_limit, disk_capacity) VALUES (?, ?, ?, ?, ?)", userID, username, cpuLimit, memoryLimit, diskCapacity)
if err != nil {
log.Fatal(err)
}
http.Redirect(w, r, "/dashboard?userID="+userID, http.StatusSeeOther)
})
http.HandleFunc("/dashboard", func(w http.ResponseWriter, r *http.Request) {
userID := r.FormValue("userID")
// Retrieve all contain records for the specified user ID
rows, err := db.Query("SELECT * FROM contain WHERE user_id = ?", userID)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var contains []Contain
for rows.Next() {
var contain Contain
err := rows.Scan(&contain.ID, &contain.UserID, &contain.IsRunning, &contain.LastUpdated, &contain.ImageID, &contain.CPUUsage, &contain.MemoryUsage, &contain.ExposedPort, &contain.ImagePackTime)
if err != nil {
log.Fatal(err)
}
contains = append(contains, contain)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
tmpl := template.Must(template.ParseFiles("templates/dashboard.html"))
tmpl.Execute(w, contains)
})
fmt.Println("Server listening on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
请注意,这只是一个示例代码,你需要根据你的实际需求进行修改和调整。同时,我也需要提醒你,这个示例代码可能存在一些漏洞和问题,请在使用前自行进行测试和验证。
阅读全文