静态文件的使用
在前端页面中,会有许多 css/js/image 等静态文件,在 gin 中只需要做以下配置。
比如项目目录如下:
然后 index.html 内容如下
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>
在主函数中做以下配置,则可以正常读取静态图片了,如下:
go
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()
}
启动后,访问浏览器,如下: