在前端页面中,会有许多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>
在主函数中做以下配置,则可以正常读取静态图片了,如下:
package mainimport ("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()}
启动后,访问浏览器,如下:
