静态文件的使用
在前端页面中,会有许多 css/js/image 等静态文件,在 gin 中只需要做以下配置。
比如项目目录如下:
然后 index.html 内容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<img src="/static/images/1.jpg" />
<h1>你好</h1>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
在主函数中做以下配置,则可以正常读取静态图片了,如下:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Hello(ctx *gin.Context){
ctx.HTML(http.StatusOK,"index.html",nil)
}
func main() {
router := gin.Default()
router.Static("/static","static")
router.LoadHTMLGlob("templates/*")
router.GET("/",Hello)
router.Run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
启动后,访问浏览器,如下:
作者:
本文链接:https://jokerbai.com
版权声明:本博客所有文章除特别声明外,均采用 署名-非商业性-相同方式共享 4.0 国际 (CC-BY-NC-SA-4.0) 许可协议。转载请注明出处!
上次更新: 2025/07/19, 09:17:41
- 02
- 使用Zadig从0到1实现持续交付平台07-19
- 03
- 基于Jira的运维发布平台07-19