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>Title</title> </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>Title</title> </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>Title</title> </head> <body> <h1>{{ .title }}</h1> </body> </html>
3、style.css
h1 { color: red; }
4、目录结构
│ main.go
│
├─static
│ └─css
│ style.css
│
└─templates
index.html
作者:iveBoy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2021-02-16 etcd+confd+nginx实现服务自动注册与发现