关于 Gin 框架加载 html 页面的一点小疑问

Jaxon · · 5235 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

新 `Gopher`,用 `Gin` 框架中碰到一些小疑问,已 `Google` 勿喷。 ## 问题描述 使用 `Gin` 加载不同文件夹下的 `index.html` 的一点疑惑,怎么加载不同文件夹下的 `index.html` 文件。 文件结构: ```html . ├── main.go └── templates ├── home │   └── index.html └── login └── index.html ``` 其中 `templates/home/index.html` 内容为: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home Title</title> </head> <body> <h1>This is Home page</h1> </body> </html> ``` 文件 `templates/login/index.html` 内容为: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login Title</title> </head> <body> <h1>This is login page</h1> </body> </html> ``` 主函数 `main.go` 文件为: ```golang package main import ( "github.com/gin-gonic/gin" "net/http" ) func LoginPage(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{}) } func HomePage(c *gin.Context) { c.HTML(http.StatusOK, "index.html", gin.H{}) } func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") router.GET("/login", LoginPage) router.GET("/home", HomePage) router.Run(":8088") } ``` 发现访问 `URL` 地址 `/login` 和 `/home` 得到相同内容: ![issue.png](https://is.golangtc.com/upload/image/6a61a92fac6611e99c202e1a8e6a359d.png) 这是终端的打印信息: ![issue - 2.png](https://is.golangtc.com/upload/image/89b5d49fac6611e99c202e1a8e6a359d.png) **希望解决的问题是:怎么样访问不同文件夹下的 `index.html` 文件**。 有试过改 `main.go` 里面的对应函数,没有成功 ``` func LoginPage(c *gin.Context) { // 之前 c.HTML(http.StatusOK, "index.html", gin.H{}) // 之后: c.HTML(http.StatusOK, "login/index.html", gin.H{}) } func IndexPage(c *gin.Context) { // 之前 c.HTML(http.StatusOK, "index.html", gin.H{}) // 之后: c.HTML(http.StatusOK, "home/index.html", gin.H{}) } ```

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

5235 次点击  ∙  1 赞  
加入收藏 微博
3 回复  |  直到 2020-02-18 18:08:44
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传