项目目录结构如下图所示:
core包下面:
class.go
package coreimport "github.com/gin-gonic/gin"func Class1(ctx *gin.Context) {}
course.go
package coreimport (. "cookie/database". "cookie/model""fmt""github.com/gin-gonic/gin""strconv"
)func CourseSubmit(ctx *gin.Context) {//tuID := ctx.Param("stuID")//fmt.Println(tuID)courseName := ctx.PostForm("kc")xf := ctx.PostForm("xf")zq := ctx.PostForm("zq")teacher := ctx.PostForm("teacher")//cla:=ctx.PostForm("class")Xf, _ := strconv.Atoi(xf)Zq, _ := strconv.Atoi(zq)Te, _ := strconv.Atoi(teacher)fmt.Println(courseName, xf, zq, teacher)var (Cou []CourseTea Teachers)DB.Where("id = ?", Te).Take(&Tea)DB.Find(&Cou)c := Course{BaseModel: BaseModel{Name: courseName},Credit: Xf,Period: Zq,TeacherID: Te,Teacher: Tea,}DB.Create(&c)fmt.Println(Cou, "-----", Tea)//重定向ctx.Redirect(301, "/course")
}func CourseSelect(ctx *gin.Context) {var co []CourseDB.Preload("Teacher").Find(&co)ctx.HTML(200, "CourseSelect.html", gin.H{"course": co,})
}func CourseADD(ctx *gin.Context) {var (Tea []Teachers)DB.Find(&Tea)//db.Find(&Cou)ctx.HTML(200, "courseADD.html", gin.H{"Tea": Tea,//"class": Cou,})
}func PostCourse(ctx *gin.Context) {var (Stud StudentsCol []Course)//获取url参数stuID := ctx.Param("stuID")//获取到url的的post请求的from表单的course多值postformArray进行参数获取CouID := ctx.PostFormArray("courseSelect")//根据参数过滤到指定的学生fmt.Println(stuID, CouID)//根据sno的ID值查询到学生信息DB.Where("sno = ?", stuID).Preload("Class.Tutor").Preload("Students").Find(&Stud)//根据post请求的值获取到对应的课程信息DB.Where("id in ?", CouID).Preload("Teacher").Find(&Col)//将学生与课程进行绑定DB.Model(&Stud).Preload("Students").Association("Course").Append(&Col)//查询有关学生的所有课程绑定信息DB.Model(&Stud).Preload("Teacher").Association("Course").Find(&Col)//服务器响应客户端,并对模板进行渲染ctx.HTML(200, "StuSelect.html", gin.H{"course": Col,"student": Stud,})
}func Course1(ctx *gin.Context) {var (Cou []CourseStu Students)//获取页面的IDstuID := ctx.Param("stuID")DB.Where("sno = ?", stuID).Take(&Stu)fmt.Println("p-------", stuID, "----------p")DB.Preload("Teacher").Find(&Cou)fmt.Println(Cou)ctx.HTML(200, "course.html", gin.H{"course": Cou,"stuID": stuID,"student": Stu,})
}
index.go
package coreimport "github.com/gin-gonic/gin"func Index(ctx *gin.Context) {ctx.HTML(200, "xcxc", gin.H{})
}
login.go
package coreimport (. "cookie/database". "cookie/model""github.com/gin-gonic/gin"
)func Login(ctx *gin.Context) {ctx.HTML(200, "login.html", nil)
}func LoginPOST(ctx *gin.Context) {var AC AccountName := ctx.PostForm("name")Pwd := ctx.PostForm("pwd")DB.Where("name = ? AND pwd = ?", Name, Pwd).Take(&AC)if AC.Id == 0 {ctx.String(200, "登入失败")} else {ctx.JSON(200, gin.H{"name": Name,"PWD": Pwd,})}}
student.go
package coreimport (. "cookie/database". "cookie/model""fmt""github.com/gin-gonic/gin""gorm.io/gorm""reflect""strconv"
)func Stu(ctx *gin.Context) {//插入数据var Student []Students//get请求里面获取头部[查询]信息Cx := ctx.Query("cx")fmt.Println("====", Cx, "====")//判断Cx的值,如果为空则显示所有,如果有值则根据值进行过滤后再进行渲染返回响应if Cx == "" {//关联预加载DB.Preload("Class.Tutor").Preload("Account").Find(&Student)} else {//关联预加载过滤查询DB.Where("Name like ?", "%"+Cx+"%").Preload("Class.Tutor").Find(&Student)}//服务器响应客户端ctx.HTML(200, "student.html", gin.H{"student": Student,})//fmt.Println(Student)
}func StudentAdd(ctx *gin.Context) {//获取class表所有数据var Cla []Class//db.json.Where("Name like ?", "软件%").Find(&Cla)DB.Find(&Cla)fmt.Println(Cla)ctx.HTML(200, "stuAdd.html", gin.H{"class": Cla,})
}func Submit(ctx *gin.Context) {//从post请求头里面抓起head内容Name := ctx.PostForm("xm")Sno := ctx.PostForm("xh")Tel := ctx.PostForm("tel")Pwd := ctx.PostForm("pw")Gender := ctx.PostForm("gender")SON, _ := strconv.Atoi(Sno)ClassID := ctx.PostForm("class")ClaID, _ := strconv.Atoi(ClassID)Gend, _ := strconv.Atoi(Gender) //字符转换成int数据类型fmt.Println(Name, Sno, Tel, Pwd, SON, ClassID, ClaID, "----")//Student := Students{BaseModel: BaseModel{Name: Name}, Pwd: Pwd, Sno: SON, Tel: Tel, ClassID: ClaID, Gender: Gend}Student := Students{BaseModel: BaseModel{Name: Name}, Sno: SON, Tel: Tel, ClassID: ClaID, Gender: Gend, Account: Account{Pwd: Pwd, BaseModel: BaseModel{Name: Name,}}}//插入数据DB.Create(&Student)//每当插入数据之后就会相应的在class的Num里面进行增+1的操作DB.Model(Class{}).Where(" Id = ?", ClassID).Update("num", gorm.Expr("num+1"))//重定向ctx.Redirect(301, "/student")
}func Delete(ctx *gin.Context) {var Student Students//获取url参数DelID := ctx.Param("DelID")fmt.Println("---WEQW----", DelID, "---EWEQ===")//删除DelID对应数据库里面sno字段参数对应的数据DB.Where("sno = ?", DelID).Delete(&Student)//重定向ctx.Redirect(301, "/student")
}func Edit(ctx *gin.Context) {var (Cla ClassStudent StudentsC []Class)//获取到页面URL参数EdiID := ctx.Param("EdiID")fmt.Println("====", EdiID, "==========")DB.Preload("Account").Where("sno = ?", EdiID).Find(&Student)//定义获取到的classDB.Where("Id = ?", Student.ClassID).Find(&Cla)//获取所有class班级信息DB.Find(&C)fmt.Println(Student.ClassID)ctx.HTML(200, "studentEdit.html", gin.H{"student": Student,"class": Cla,"claAll": C,})
}func UpEdit(ctx *gin.Context) {//从post请求头里面抓起head内容Name := ctx.PostForm("xm")Sno := ctx.PostForm("xh")Tel := ctx.PostForm("tel")Pwd := ctx.PostForm("pw")Gender := ctx.PostForm("gender")SON, _ := strconv.Atoi(Sno)ClassID := ctx.PostForm("class")ClaID, _ := strconv.Atoi(ClassID)Gend, _ := strconv.Atoi(Gender) //字符转换成int数据类型fmt.Println(Name, Sno, Tel, Pwd, SON, ClassID, ClaID, Gender, "----")//修改账户密码,在go语言里面不支持修改嵌套在结构体内的值,不会更新级联嵌套结构体里面的字段。var (Student StudentsAc Account)account := DB.Where("sno = ?", SON).Preload("Account").Find(&Student)fmt.Println(reflect.TypeOf(account), account)if account.Error != nil {fmt.Println(account.Error)}fmt.Println("ppppppppppppppppppppppppp->", Student.AccountID, Student)result := DB.Model(Ac).Where("id = ? ", Student.AccountID).Update("Pwd", Pwd)//Student := Students{BaseModel: BaseModel{Name: Name}, Pwd: Pwd, Sno: SON, Tel: Tel, ClassID: ClaID, Gender: Gend}student := Students{BaseModel: BaseModel{Name: Name}, Sno: SON, Tel: Tel, ClassID: ClaID, Gender: Gend}fmt.Println(Student)result2 := DB.Model(Students{}).Where("sno = ?", SON).Updates(student)if result.Error != nil {fmt.Printf("Error updating student: %v\n", result2.Error)}/*重定向:客户端访问/student/submit表单页面进行数据提交;服务器响应客户端【空值】;客户端第二次向服务端发出/student页面请求;服务端再次根据请求将/student页面响应客户端;一次请求两个响应,一次空响应,第二次为跳转之后的响应页面数据*/ctx.Redirect(301, "/student")
}func StuSelect(ctx *gin.Context) {var (Student StudentsCol []Course)//获取页面的IDstuID := ctx.Param("stuID")fmt.Println("p-------", stuID, "----------p")DB.Where("sno = ? ", stuID).Preload("Class.Tutor").Preload("Account").Find(&Student)fmt.Println(Student)//获取到学生对应的课程信息DB.Model(&Student).Preload("Teacher").Preload("Account").Association("Course").Find(&Col)ctx.HTML(200, "StuSelect.html", gin.H{"student": Student,"course": Col,})
}
databases包下面
mysql.go
package databaseimport (. "cookie/model""fmt""gorm.io/driver/mysql""gorm.io/gorm""gorm.io/gorm/logger""log""os""reflect"
)var DB *gorm.DB// 数据库初始化
func DbInit() *gorm.DB {newLogger := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), // io writerlogger.Config{//SlowThreshold: time.Second, // 慢 SQL 阈值LogLevel: logger.Info, // Log level},)fmt.Println(reflect.TypeOf(newLogger))dsn := "xxx:xxxx@tcp(xxxx:xxxx)/css4?charset=utf8mb4&parseTime=True&loc=Local"DB, _ = gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger,})//调用gorm根据go语言的结构体去创建mysql一一对应的表DB.AutoMigrate(&Teachers{},&Class{},&Course{},&Students{},&Account{},&AdminUser{},)//先删除表DB.Migrator().DropTable(&Teachers{}, &Class{}, &Course{}, &Students{}, &Account{}, &AdminUser{})//再重建表DB.AutoMigrate(&Teachers{}, &Class{}, &Course{}, &Students{}, &AdminUser{})return DB
}
model包下面
rbac.go
package modeltype Account struct {BaseModelPwd string
}
student.go
package modelimport "time"type Course struct {BaseModelCredit intPeriod intTeacherID intTeacher Teachers `gorm:"foreignkey:TeacherID"`
}type Class struct {BaseModelNum intTutorID intTutor Teachers `gorm:"foreignkey:TutorID"`
}type Students struct {BaseModelSno int `gorm:"unique"`//Pwd string `gorm:"type:varchar(100);not null"`Tel string `gorm:"type:char(11);"`Gender intBrith *time.TimeRemark string `gorm:"type:varchar(255);"`//多对一ClassID intClass Class `gorm:"foreignkey:ClassID;constraint:OnDelete:CASCADE;"`//多对多Course []Course `gorm:"many2many:student2course;constraint:OnDelete:CASCADE;"`//一对一AccountID int `gorm:"unique"`Account Account `gorm:"constraint:OnDelete:CASCADE;"`
}type AdminUser struct {Id int `gorm:"primarykey"`AccountID int `gorm:"unique"`Account Account
}type BaseModel struct {Id int `gorm:"primarykey"`CreateTime *time.Time `gorm:"autoCreateTime"`UpdateTime *time.Time `gorm:"autoCreateTime"`Name string `gorm:"type:varchar(30);unique;not null"`
}type Teachers struct {BaseModelTon int `gorm:"unique"`//Pwd string `gorm:"type:varchar(100);not null"`Tel string `gorm:"type:char(11);"`Birth *time.TimeRemark string `gorm:"type:varchar(255);"`//一对一AccountID int `gorm:"unique"`Account Account
}
rander包下面
index.go
package randerimport ("github.com/gin-contrib/multitemplate""html/template""log"
)// 创建累加函数
func addOne(i int) int {return i + 1
}func CreateMyRender() multitemplate.Renderer {// 创建功能映射funcMap := template.FuncMap{"addOne": addOne,}templates, err := template.New("StuSelect.html").Funcs(funcMap).ParseFiles("template/publi.html", "template/StuSelect.html")if err != nil {log.Fatalf("Failed to create template 'xcxc': %v", err)}r := multitemplate.NewRenderer()r.AddFromFiles("xcxc", "template/publi.html", "template/index.html") //xcxc 为组合后的模板名称,与函数内的名字保持一致即可r.AddFromFiles("student.html", "template/publi.html", "template/student.html")r.AddFromFiles("stuAdd.html", "template/publi.html", "template/studentAdd.html")r.AddFromFiles("course.html", "template/publi.html", "template/course.html")r.AddFromFiles("clss.html", "template/publi.html", "template/class.html")r.AddFromFiles("studentADD.html", "template/publi.html", "template/jixuADD.html")r.AddFromFiles("studentEdit.html", "template/publi.html", "template/studentEdit.html")//r.AddFromFiles("StuSelect.html", "template/publi.html", "template/StuSelect.html")r.Add("StuSelect.html", templates)r.AddFromFiles("courseADD.html", "template/publi.html", "template/courseADD.html")r.AddFromFiles("CourseSelect.html", "template/publi.html", "template/CourseSelect.html")r.AddFromFiles("login.html", "template/LoginStu.html")return r/*在Gin框架中注册自定义函数addOne,并在名为StuSelect.html的模板中使用它。错误panic: template: StuSelect.html:46: function "addOne" not defined表明在解析模板的过程中模板引擎尝试查找并执行addOne函数,但是没有找到这个函数的定义。要解决这个问题,你需要确保以下几点:自定义函数addOne确实已经在你的代码中定义了。这个函数通过适当的FuncMap注册到了Gin框架的模板中。这个注册的函数在模板中使用的时候要匹配函数映射中的键(即函数名)。你的代码中的错误是因为你在Gin的默认模板渲染器HTMLRender中并没有正确地注册自定义的函数映射。你使用了multitemplate.NewRenderer()来创建新的多模板渲染器,但在创建这个渲染器的过程中,并没有将自定义函数addOne加入到FuncMap中。你在main函数中尝试注册addOne到"StuSelect.html"模板,并设置它为Gin的HTML渲染器。这个操作并不能应用到multitemplate.Renderer上。由于multitemplate.Renderer处理多模板的方式不同,你的自定义函数需要通过不同的方式注册。为了将自定义函数addOne注册到你所有使用multitemplate.Renderer的模板中,你需要在每个AddFromFiles调用中创建一个新的template.Template,将FuncMap添加到这个模板,并且使用它们来创建各自的页面模板。修改createMyRender函数,像这样注册你的自定义函数:gofunc createMyRender() multitemplate.Renderer {funcMap := template.FuncMap{"addOne": addOne,}r := multitemplate.NewRenderer()// 这里以"xcxc"为例,其他模板类似地处理templates, err := template.New("publi.html").Funcs(funcMap).ParseFiles("template/publi.html", "template/index.html")if err != nil {log.Fatalf("Failed to create template 'xcxc': %v", err)}r.Add("xcxc", templates)// ...其他模板注册代码return r}请确保使用Funcs和ParseFiles的顺序是正确的,并且处理了所有可能发生的错误。这样做能够确保所有使用multitemplate.Renderer的模板都注册了addOne函数。最后,记得删除main函数中重新注册StuSelect.html模板和设置HTML渲染器的代码,因为这个操作应该在createMyRender函数内完成。所有模板都应该通过multitemplate.Renderer来创建和注册。在您提供的代码中,“xcxc”是一个在multitemplate.NewRenderer()中注册的模板的名称。在Gin框架中,multitemplate是一个用来支持多模板渲染的扩展包。使用这个扩展包的NewRenderer()方法可以创建一个新的渲染器,它能允许您为不同的路由定义不同的模板布局。在创建这些模板时,您可以为这些组合好的模板指定任意的名字,名称是自定义的,对系统没有具体的意义,但是应该反映出模板的内容或用途,让人一看就能理解这个模板的作用。在这里,xcxc可能是开发者随意给出的一个示例名称,或者特定于应用程序上下文的内部命名。举例来说,以下代码创建了一个名为xcxc的组合模板,该模板由"template/publi.html"和"template/index.html"这两个文件组合而成:gor.AddFromFiles("xcxc", "template/publi.html", "template/index.html")在这段代码中,"xcxc"是您可以在Gin的路由处理函数中使用的模板名。例如:gofunc index(ctx *gin.Context) {ctx.HTML(http.StatusOK, "xcxc", gin.H{// 模板数据...})}在这个index函数中,调用ctx.HTML方法时使用了"xcxc"作为模板名称,这告诉Gin渲染器要使用我们定义的包含名为"xcxc"的组合模板来生成响应的HTML。总结来说,"xcxc"在您提供的代码示例中只是一个随意的模板名称,它在Gin的路由处理中用来引用特定的模板组合。您完全可以根据自己的需要将它改为更具描述性的名称。*/
}
route路由包下面
class.go
package routeimport (. "cookie/core""github.com/gin-gonic/gin"
)func ClassRoute(r *gin.Engine) {r.GET("/class", Class1)
}
course.go
package routeimport (. "cookie/core""github.com/gin-gonic/gin"
)func CourseRoute(r *gin.RouterGroup) {r.GET("/", CourseSelect)r.GET("/add", CourseADD)r.POST("/submit", CourseSubmit)
}
index.go
package routeimport (. "cookie/core""github.com/gin-gonic/gin"
)func IndexRoute(r *gin.Engine) {//动态路由r.GET("/", Index)
}
InitRoute.go
package routeimport ("github.com/gin-gonic/gin"
)func InitRoute(r *gin.Engine) {stuent := r.Group("/student")course := r.Group("/course")//动态路由IndexRoute(r)StudenRoute(stuent)ClassRoute(r)LoginRoute(r)CourseRoute(course)}
login.go
package routeimport (. "cookie/core""github.com/gin-gonic/gin"
)func LoginRoute(r *gin.Engine) {r.GET("/login", Login)r.POST("/login", LoginPOST)
}
student.go
package routeimport (. "cookie/core""github.com/gin-gonic/gin"
)func StudenRoute(r *gin.RouterGroup) {r.GET("/edit/:EdiID", Edit)r.POST("/", UpEdit)r.POST("/submit", Submit)r.GET("/:stuID/StuSelect", StuSelect)r.POST("/:stuID/StuSelect", PostCourse)r.GET("/", Stu)r.GET("/:stuID/course", Course1)
}
最后mian.go
package mainimport (. "cookie/database". "cookie/rander". "cookie/route""github.com/gin-gonic/gin"
)func main() {//数据库初始化DbInit()//构gin引擎r := gin.Default()//加载静态文件r.Static("/static", "./static")//多模块加载,渲染r.HTMLRender = CreateMyRender()InitRoute(r)//运行go引擎r.Run(":8888")}