如何在 Gin 路由器中呈现静态文件?
How to render static files within Gin router?
我想用 gin 服务器提供一个 JSON 文件。并在 HTML 文件中设置一些自定义值。在其中使用JavaScript调用JSON文件。
我的申请结构:
.
├── main.go
└── templates
├── index.html
└── web.json
我将这些基本源代码放入 main.go
文件中:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
var router *gin.Engine
func main() {
router = gin.Default()
router.LoadHTMLGlob("templates/*")
router.GET("/web", func(c *gin.Context) {
c.HTML(
http.StatusOK,
"index.html",
gin.H{
"title": "Web",
"url": "./web.json",
},
)
})
router.Run()
}
templates/index.html
文件中的一些代码:
<!doctype html>
<html>
<head>
<title>{{ .title }}</title>
// ...
</head>
<body>
<div id="swagger-ui"></div>
// ...
<script>
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "{{ .url }}",
dom_id: '#swagger-ui',
// ...
})
// End Swagger UI call region
window.ui = ui
}
</script>
</body>
</html>
当运行应用程序时,我得到一个获取错误:
Not Found ./web.json
那么我应该如何在 Gin 内部服务器中提供要访问的 web.json
文件?
引用原始 gin 文档:https://github.com/gin-gonic/gin#serving-static-files
func main() {
router := gin.Default()
router.Static("/assets", "./assets")
router.StaticFS("/more_static", http.Dir("my_file_system"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// Listen and serve on 0.0.0.0:8080
router.Run(":8080")
}
所以基本上你应该在你定义的其他路由旁边定义一个特定于你的 JSON 文件的路由。然后使用那个。
我想用 gin 服务器提供一个 JSON 文件。并在 HTML 文件中设置一些自定义值。在其中使用JavaScript调用JSON文件。
我的申请结构:
.
├── main.go
└── templates
├── index.html
└── web.json
我将这些基本源代码放入 main.go
文件中:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
var router *gin.Engine
func main() {
router = gin.Default()
router.LoadHTMLGlob("templates/*")
router.GET("/web", func(c *gin.Context) {
c.HTML(
http.StatusOK,
"index.html",
gin.H{
"title": "Web",
"url": "./web.json",
},
)
})
router.Run()
}
templates/index.html
文件中的一些代码:
<!doctype html>
<html>
<head>
<title>{{ .title }}</title>
// ...
</head>
<body>
<div id="swagger-ui"></div>
// ...
<script>
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "{{ .url }}",
dom_id: '#swagger-ui',
// ...
})
// End Swagger UI call region
window.ui = ui
}
</script>
</body>
</html>
当运行应用程序时,我得到一个获取错误:
Not Found ./web.json
那么我应该如何在 Gin 内部服务器中提供要访问的 web.json
文件?
引用原始 gin 文档:https://github.com/gin-gonic/gin#serving-static-files
func main() {
router := gin.Default()
router.Static("/assets", "./assets")
router.StaticFS("/more_static", http.Dir("my_file_system"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// Listen and serve on 0.0.0.0:8080
router.Run(":8080")
}
所以基本上你应该在你定义的其他路由旁边定义一个特定于你的 JSON 文件的路由。然后使用那个。