
Gin引用静态文件
1.准备HTML模板
1.下载模板https://www.51qianduan.com/temp/19883.html#
修改此位置/assets
<!-- CSS --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500"> <link rel="stylesheet" href="/assets/bootstrap/css/bootstrap.min.css">项目路径如下
C:. ├─static │ ├─bootstrap │ │ ├─css │ │ ├─fonts │ │ └─js │ ├─css │ ├─font-awesome │ │ ├─css │ │ ├─fonts │ │ ├─less │ │ └─scss │ ├─ico │ ├─img │ │ └─backgrounds │ └─js └─templates │ └─login.go修改login.html文件
<div class="form-bottom"> <form role="form" action="" method="post" class="registration-form"> <div class="form-group"> <label class="sr-only" for="form-first-name">First name</label> <input type="text" name="username" placeholder="username..." class="form-first-name form-control"> </div> <div class="form-group"> <label class="sr-only" for="form-last-name">Last name</label> <input type="password" name="password" placeholder="password" class="form-last-name form-control"> </div> <button type="submit" class="btn">登陆</button> <p style="color: red">{{ .errMessage }}</p> </form> </div>增加index.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h1>index html</h1> </body> </html>
2.编写login.go主程序
1.前后端字段username和password要对应
package main import ( "net/http" "github.com/gin-gonic/gin" ) type user struct { Username string `form:"username"` Password string `form:"password"` } func postLoginHandler(c *gin.Context) { //获取用户输入 var u user err := c.ShouldBind(&u) if err != nil { c.HTML(http.StatusOK, "login.html", gin.H{ "errMessage": "用户名或者密码参数有误", }) return } if len(u.Username) == 0 || len(u.Password) == 0 { c.HTML(http.StatusOK, "login.html", gin.H{ "errMessage": "用户名或者密码为空", }) return } //去数据库校验用户名和密码书否正确 c.Redirect(http.StatusFound, "/index") } func main() { r := gin.Default() //1.加载静态文件 r.Static("/assets", "./static") //2.自定义模板函数 //3.加载模板文件 r.LoadHTMLGlob("templates/*") //GET:跟server端要一个登陆页面 r.GET("/login", func(c *gin.Context) { c.HTML(http.StatusOK, "login.html", nil) }) /* r.POST("/login", func(c *gin.Context) { c.HTML(http.StatusOK, "login.html", nil) }) */ r.POST("/login", postLoginHandler) r.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", nil) }) r.Run(":8081") }
