Gin框架系列之静态文件
一、模板引入
在进行Web开发中,你可能进行的项目是前后端不分离的情况,此时需要将html与后端放入一个工程中,gin框架支持这种做法,需要通过 LoadHTMLGlob() 或 LoadHTMLFiles()。
(一)LoadHTMLFiles
故名思义就是加载文件
1、main.go
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { router := gin.Default() router.LoadHTMLFiles("templates/index.html") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{ "title": "main site", }) }) router.Run(":8000") }
2、index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
{{ .title }}
body>
html>
3、目录结构
│ main.go
│
└─templates
index.html
此时需要进入当前目录,通过go run main.go运行,否则会出现找不到路径的情况。
(二)LoadHTMLGlob
可以以指定的模式匹配文件:
func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") //加载templates目录下所有文件 router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{ "title": "main site", }) }) router.Run(":8000") }
另外就是可以解决不同目录下同名文件问题。
1、main.go
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{ "title": "main site", }) }) router.GET("/users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{ "title": "users site", }) }) router.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{ "title": "posts site", }) }) router.Run(":8000") }
2、index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
{{ .title }}
body>
html>
3、目录结构
│ main.go
│
└─templates
│ index.html
│
├─posts
│ index.html
│
└─users
index.html
二、静态资源引入
在进行不分离的开发情况下,通过会有css、js、image等资源的引入。
1、main.go
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { router := gin.Default() router.LoadHTMLFiles("templates/index.html") /* 表示只要静态资源的路径是以/static开头的,就去项目根路径的static目录下寻找 在index.html文件中引入静态资源刚好是以/static开头的 */ router.Static("/static", "./static") //router.StaticFS("/static", http.Dir("./static")) router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{ "title": "main site", }) }) router.Run(":8000") }
2、index.html
DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="/static/css/style.css">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>{{ .title }}h1>
body>
html>
3、style.css
h1 { color: red; }
4、目录结构
│ main.go
│
├─static
│ └─css
│ style.css
│
└─templates
index.html